repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
GoogleCloudPlatform/runtime-builder-java
java-runtime-builder-app/src/main/java/com/google/cloud/runtimes/builder/config/domain/BuildContext.java
// Path: java-runtime-builder-app/src/main/java/com/google/cloud/runtimes/builder/util/StringLineAppender.java // public class StringLineAppender { // // private List<String> lines; // // public StringLineAppender(String... initalLines) { // lines = new LinkedList<>(); // Arrays.stream(initalLines).forEach(this::appendLine); // } // // public StringLineAppender() { // lines = new LinkedList<>(); // } // // /** // * Appends a line to the internal buffer. Newline characters are not required. // */ // public StringLineAppender appendLine(String line) { // lines.add(line); // return this; // } // // /** // * Appends an empty line to the internal buffer. Newline characters are not required. // */ // public StringLineAppender appendLine() { // lines.add(""); // return this; // } // // /** // * Prepends an empty line to the internal buffer. Newline characters are not required. // */ // public StringLineAppender prependLine() { // lines.add(0, ""); // return this; // } // // public List<String> getLines() { // return lines; // } // // public void setLines(List<String> lines) { // this.lines = lines; // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // for (String line : lines) { // builder.append(line + System.lineSeparator()); // } // return builder.toString(); // } // // }
import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.WRITE; import com.google.cloud.runtimes.builder.injection.DisableSourceBuild; import com.google.cloud.runtimes.builder.util.StringLineAppender; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors;
/* * Copyright 2017 Google Inc. All Rights Reserved. * * 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.google.cloud.runtimes.builder.config.domain; /** * Encapsulates information about the build's state. Mediates interactions with the build directory * and stores build configuration. */ public class BuildContext { private static final String DOCKERFILE_NAME = "Dockerfile"; private static final List<String> EXISITING_DOCKER_PATHS = ImmutableList.of(DOCKERFILE_NAME, "src/main/docker/" + DOCKERFILE_NAME); private static final String DOCKERIGNORE_NAME = ".dockerignore"; private final Logger logger = LoggerFactory.getLogger(BuildContext.class); private final AppYaml appYaml; private final Path workspaceDir;
// Path: java-runtime-builder-app/src/main/java/com/google/cloud/runtimes/builder/util/StringLineAppender.java // public class StringLineAppender { // // private List<String> lines; // // public StringLineAppender(String... initalLines) { // lines = new LinkedList<>(); // Arrays.stream(initalLines).forEach(this::appendLine); // } // // public StringLineAppender() { // lines = new LinkedList<>(); // } // // /** // * Appends a line to the internal buffer. Newline characters are not required. // */ // public StringLineAppender appendLine(String line) { // lines.add(line); // return this; // } // // /** // * Appends an empty line to the internal buffer. Newline characters are not required. // */ // public StringLineAppender appendLine() { // lines.add(""); // return this; // } // // /** // * Prepends an empty line to the internal buffer. Newline characters are not required. // */ // public StringLineAppender prependLine() { // lines.add(0, ""); // return this; // } // // public List<String> getLines() { // return lines; // } // // public void setLines(List<String> lines) { // this.lines = lines; // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // for (String line : lines) { // builder.append(line + System.lineSeparator()); // } // return builder.toString(); // } // // } // Path: java-runtime-builder-app/src/main/java/com/google/cloud/runtimes/builder/config/domain/BuildContext.java import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.WRITE; import com.google.cloud.runtimes.builder.injection.DisableSourceBuild; import com.google.cloud.runtimes.builder.util.StringLineAppender; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /* * Copyright 2017 Google Inc. All Rights Reserved. * * 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.google.cloud.runtimes.builder.config.domain; /** * Encapsulates information about the build's state. Mediates interactions with the build directory * and stores build configuration. */ public class BuildContext { private static final String DOCKERFILE_NAME = "Dockerfile"; private static final List<String> EXISITING_DOCKER_PATHS = ImmutableList.of(DOCKERFILE_NAME, "src/main/docker/" + DOCKERFILE_NAME); private static final String DOCKERIGNORE_NAME = ".dockerignore"; private final Logger logger = LoggerFactory.getLogger(BuildContext.class); private final AppYaml appYaml; private final Path workspaceDir;
private final StringLineAppender dockerfile;
ligi/AXT
src/test/java/org/ligi/axt/test/TheEditTextAXT.java
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // }
import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail;
package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheEditTextAXT { private final static String TEXT2SET = "foobar"; @Test public void should_set_text_when_needed() { EditText editText = new EditText(RuntimeEnvironment.application);
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // } // Path: src/test/java/org/ligi/axt/test/TheEditTextAXT.java import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheEditTextAXT { private final static String TEXT2SET = "foobar"; @Test public void should_set_text_when_needed() { EditText editText = new EditText(RuntimeEnvironment.application);
AXT.at(editText).changeTextIfNeeded(TEXT2SET);
ligi/AXT
src/test/java/org/ligi/axt/test/TheArrayAXT.java
// Path: src/test/java/org/ligi/CustomRobolectricRunner.java // public class CustomRobolectricRunner extends RobolectricTestRunner { // public CustomRobolectricRunner(Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected AndroidManifest getAppManifest(Config config) { // String manifestPath = "AndroidManifest.xml"; // String resPath = "build/intermediates/res/" + BuildConfig.BUILD_TYPE; // // // android studio has a different execution root for tests than pure gradle // // so we avoid here manual effort to get them running inside android studio // if (!new File(manifestPath).exists()) { // manifestPath = "app/" + manifestPath; // } // // config = overwriteConfig(config, "manifest", manifestPath); // config = overwriteConfig(config, "resourceDir", resPath); // return super.getAppManifest(config); // } // // private Config.Implementation overwriteConfig(Config config, String key, String value) { // Properties properties = new Properties(); // properties.setProperty(key, value); // return new Config.Implementation(config, Config.Implementation.fromProperties(properties)); // } // // } // // Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // }
import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.CustomRobolectricRunner; import org.ligi.axt.AXT; import org.ligi.axt.extensions.ArrayAXT; import static org.assertj.core.api.Assertions.assertThat;
package org.ligi.axt.test; @RunWith(CustomRobolectricRunner.class) public class TheArrayAXT { @Test public void should_proper_combine_byte_arrays() {
// Path: src/test/java/org/ligi/CustomRobolectricRunner.java // public class CustomRobolectricRunner extends RobolectricTestRunner { // public CustomRobolectricRunner(Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected AndroidManifest getAppManifest(Config config) { // String manifestPath = "AndroidManifest.xml"; // String resPath = "build/intermediates/res/" + BuildConfig.BUILD_TYPE; // // // android studio has a different execution root for tests than pure gradle // // so we avoid here manual effort to get them running inside android studio // if (!new File(manifestPath).exists()) { // manifestPath = "app/" + manifestPath; // } // // config = overwriteConfig(config, "manifest", manifestPath); // config = overwriteConfig(config, "resourceDir", resPath); // return super.getAppManifest(config); // } // // private Config.Implementation overwriteConfig(Config config, String key, String value) { // Properties properties = new Properties(); // properties.setProperty(key, value); // return new Config.Implementation(config, Config.Implementation.fromProperties(properties)); // } // // } // // Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // } // Path: src/test/java/org/ligi/axt/test/TheArrayAXT.java import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.CustomRobolectricRunner; import org.ligi.axt.AXT; import org.ligi.axt.extensions.ArrayAXT; import static org.assertj.core.api.Assertions.assertThat; package org.ligi.axt.test; @RunWith(CustomRobolectricRunner.class) public class TheArrayAXT { @Test public void should_proper_combine_byte_arrays() {
Byte[] test = AXT.at(new Byte[]{23, 5}).combineWith(new Byte[]{42, 6});
ligi/AXT
src/test/java/org/ligi/axt/test/TheBitmapAXT.java
// Path: src/test/java/org/ligi/CustomRobolectricRunner.java // public class CustomRobolectricRunner extends RobolectricTestRunner { // public CustomRobolectricRunner(Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected AndroidManifest getAppManifest(Config config) { // String manifestPath = "AndroidManifest.xml"; // String resPath = "build/intermediates/res/" + BuildConfig.BUILD_TYPE; // // // android studio has a different execution root for tests than pure gradle // // so we avoid here manual effort to get them running inside android studio // if (!new File(manifestPath).exists()) { // manifestPath = "app/" + manifestPath; // } // // config = overwriteConfig(config, "manifest", manifestPath); // config = overwriteConfig(config, "resourceDir", resPath); // return super.getAppManifest(config); // } // // private Config.Implementation overwriteConfig(Config config, String key, String value) { // Properties properties = new Properties(); // properties.setProperty(key, value); // return new Config.Implementation(config, Config.Implementation.fromProperties(properties)); // } // // } // // Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // }
import android.graphics.Bitmap; import android.graphics.Point; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.CustomRobolectricRunner; import org.ligi.axt.AXT;
package org.ligi.axt.test; @RunWith(CustomRobolectricRunner.class) public class TheBitmapAXT { public static final int SIZE_X_PROBE = 42; public static final int SIZE_Y_PROBE = 100; @Test public void size_as_point_works() { Bitmap origBitmap = Bitmap.createBitmap(SIZE_X_PROBE, SIZE_Y_PROBE, Bitmap.Config.ARGB_8888);
// Path: src/test/java/org/ligi/CustomRobolectricRunner.java // public class CustomRobolectricRunner extends RobolectricTestRunner { // public CustomRobolectricRunner(Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected AndroidManifest getAppManifest(Config config) { // String manifestPath = "AndroidManifest.xml"; // String resPath = "build/intermediates/res/" + BuildConfig.BUILD_TYPE; // // // android studio has a different execution root for tests than pure gradle // // so we avoid here manual effort to get them running inside android studio // if (!new File(manifestPath).exists()) { // manifestPath = "app/" + manifestPath; // } // // config = overwriteConfig(config, "manifest", manifestPath); // config = overwriteConfig(config, "resourceDir", resPath); // return super.getAppManifest(config); // } // // private Config.Implementation overwriteConfig(Config config, String key, String value) { // Properties properties = new Properties(); // properties.setProperty(key, value); // return new Config.Implementation(config, Config.Implementation.fromProperties(properties)); // } // // } // // Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // } // Path: src/test/java/org/ligi/axt/test/TheBitmapAXT.java import android.graphics.Bitmap; import android.graphics.Point; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.CustomRobolectricRunner; import org.ligi.axt.AXT; package org.ligi.axt.test; @RunWith(CustomRobolectricRunner.class) public class TheBitmapAXT { public static final int SIZE_X_PROBE = 42; public static final int SIZE_Y_PROBE = 100; @Test public void size_as_point_works() { Bitmap origBitmap = Bitmap.createBitmap(SIZE_X_PROBE, SIZE_Y_PROBE, Bitmap.Config.ARGB_8888);
Point sizeAsPoint = AXT.at(origBitmap).getSizeAsPoint();
ligi/AXT
src/test/java/org/ligi/axt/test/TheRepeatedOnClicksListener.java
// Path: src/main/java/org/ligi/axt/listeners/RepeatedOnClicksListener.java // public class RepeatedOnClicksListener implements View.OnClickListener { // // private final View.OnClickListener listener; // private final int configuredClicksBeforeFiring; // private int actClicksBeforeFiring; // private boolean repeatsAreAllowed = true; // private int callCount; // // public RepeatedOnClicksListener(int clickCountBeforeFire, View.OnClickListener listener) { // this.listener = listener; // this.configuredClicksBeforeFiring = clickCountBeforeFire; // this.actClicksBeforeFiring = configuredClicksBeforeFiring; // callCount = 0; // } // // @Override // public void onClick(View view) { // if (callCount == 0 || repeatsAreAllowed) { // if (actClicksBeforeFiring-- <= 0) { // listener.onClick(view); // actClicksBeforeFiring = configuredClicksBeforeFiring; // callCount++; // } // } // } // // public RepeatedOnClicksListener doNotRepeatCalls() { // repeatsAreAllowed = false; // return this; // } // // public int getCallCount() { // return callCount; // } // // }
import android.view.View; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.listeners.RepeatedOnClicksListener; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import static android.view.View.OnClickListener; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheRepeatedOnClicksListener { @Mock private OnClickListener listener; @Mock private View view; @Before public void before() { MockitoAnnotations.initMocks(this); } @Test public void should_not_fire_when_not_clicked() {
// Path: src/main/java/org/ligi/axt/listeners/RepeatedOnClicksListener.java // public class RepeatedOnClicksListener implements View.OnClickListener { // // private final View.OnClickListener listener; // private final int configuredClicksBeforeFiring; // private int actClicksBeforeFiring; // private boolean repeatsAreAllowed = true; // private int callCount; // // public RepeatedOnClicksListener(int clickCountBeforeFire, View.OnClickListener listener) { // this.listener = listener; // this.configuredClicksBeforeFiring = clickCountBeforeFire; // this.actClicksBeforeFiring = configuredClicksBeforeFiring; // callCount = 0; // } // // @Override // public void onClick(View view) { // if (callCount == 0 || repeatsAreAllowed) { // if (actClicksBeforeFiring-- <= 0) { // listener.onClick(view); // actClicksBeforeFiring = configuredClicksBeforeFiring; // callCount++; // } // } // } // // public RepeatedOnClicksListener doNotRepeatCalls() { // repeatsAreAllowed = false; // return this; // } // // public int getCallCount() { // return callCount; // } // // } // Path: src/test/java/org/ligi/axt/test/TheRepeatedOnClicksListener.java import android.view.View; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.listeners.RepeatedOnClicksListener; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import static android.view.View.OnClickListener; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheRepeatedOnClicksListener { @Mock private OnClickListener listener; @Mock private View view; @Before public void before() { MockitoAnnotations.initMocks(this); } @Test public void should_not_fire_when_not_clicked() {
new RepeatedOnClicksListener(1, listener);
ligi/AXT
src/test/java/org/ligi/axt/test/TheSeekbarMinMax.java
// Path: src/main/java/org/ligi/axt/views/SeekBarMinMax.java // public class SeekBarMinMax extends SeekBar { // // private final int min; // // public SeekBarMinMax(Context context, int min, int max) { // super(context); // // if (min > max) { // throw new IllegalArgumentException("max must be bigger than min for SeegBarMinMax"); // } // // this.min = min; // this.setMax(max - min); // } // // @Override // public synchronized int getProgress() { // return super.getProgress() + min; // } // // @Override // public synchronized void setProgress(int progress) { // super.setProgress(progress - min); // } // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.views.SeekBarMinMax; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail;
package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheSeekbarMinMax {
// Path: src/main/java/org/ligi/axt/views/SeekBarMinMax.java // public class SeekBarMinMax extends SeekBar { // // private final int min; // // public SeekBarMinMax(Context context, int min, int max) { // super(context); // // if (min > max) { // throw new IllegalArgumentException("max must be bigger than min for SeegBarMinMax"); // } // // this.min = min; // this.setMax(max - min); // } // // @Override // public synchronized int getProgress() { // return super.getProgress() + min; // } // // @Override // public synchronized void setProgress(int progress) { // super.setProgress(progress - min); // } // } // Path: src/test/java/org/ligi/axt/test/TheSeekbarMinMax.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.views.SeekBarMinMax; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheSeekbarMinMax {
private SeekBarMinMax tested;
ligi/AXT
src/test/java/org/ligi/axt/test/TheViewAXT.java
// Path: src/test/java/org/ligi/CustomRobolectricRunner.java // public class CustomRobolectricRunner extends RobolectricTestRunner { // public CustomRobolectricRunner(Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected AndroidManifest getAppManifest(Config config) { // String manifestPath = "AndroidManifest.xml"; // String resPath = "build/intermediates/res/" + BuildConfig.BUILD_TYPE; // // // android studio has a different execution root for tests than pure gradle // // so we avoid here manual effort to get them running inside android studio // if (!new File(manifestPath).exists()) { // manifestPath = "app/" + manifestPath; // } // // config = overwriteConfig(config, "manifest", manifestPath); // config = overwriteConfig(config, "resourceDir", resPath); // return super.getAppManifest(config); // } // // private Config.Implementation overwriteConfig(Config config, String key, String value) { // Properties properties = new Properties(); // properties.setProperty(key, value); // return new Config.Implementation(config, Config.Implementation.fromProperties(properties)); // } // // } // // Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // }
import android.view.View; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.CustomRobolectricRunner; import org.ligi.axt.AXT; import org.robolectric.RuntimeEnvironment; import static org.assertj.core.api.Assertions.assertThat;
package org.ligi.axt.test; @RunWith(CustomRobolectricRunner.class) public class TheViewAXT { @Test public void should_correctly_set_visibility() { View v = new View(RuntimeEnvironment.application);
// Path: src/test/java/org/ligi/CustomRobolectricRunner.java // public class CustomRobolectricRunner extends RobolectricTestRunner { // public CustomRobolectricRunner(Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected AndroidManifest getAppManifest(Config config) { // String manifestPath = "AndroidManifest.xml"; // String resPath = "build/intermediates/res/" + BuildConfig.BUILD_TYPE; // // // android studio has a different execution root for tests than pure gradle // // so we avoid here manual effort to get them running inside android studio // if (!new File(manifestPath).exists()) { // manifestPath = "app/" + manifestPath; // } // // config = overwriteConfig(config, "manifest", manifestPath); // config = overwriteConfig(config, "resourceDir", resPath); // return super.getAppManifest(config); // } // // private Config.Implementation overwriteConfig(Config config, String key, String value) { // Properties properties = new Properties(); // properties.setProperty(key, value); // return new Config.Implementation(config, Config.Implementation.fromProperties(properties)); // } // // } // // Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // } // Path: src/test/java/org/ligi/axt/test/TheViewAXT.java import android.view.View; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.CustomRobolectricRunner; import org.ligi.axt.AXT; import org.robolectric.RuntimeEnvironment; import static org.assertj.core.api.Assertions.assertThat; package org.ligi.axt.test; @RunWith(CustomRobolectricRunner.class) public class TheViewAXT { @Test public void should_correctly_set_visibility() { View v = new View(RuntimeEnvironment.application);
AXT.at(v).setVisibility(false);
ligi/AXT
src/test/java/org/ligi/axt/test/TheCheckBoxAXT.java
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // }
import android.widget.CheckBox; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.junit.Assert.assertEquals;
package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheCheckBoxAXT { @Test public void should_sync() { CheckBox checkBox1 = new CheckBox(RuntimeEnvironment.application);
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // } // Path: src/test/java/org/ligi/axt/test/TheCheckBoxAXT.java import android.widget.CheckBox; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.junit.Assert.assertEquals; package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheCheckBoxAXT { @Test public void should_sync() { CheckBox checkBox1 = new CheckBox(RuntimeEnvironment.application);
AXT.at(checkBox1).careForCheckedStatePersistence("SAME_TAG");
ligi/AXT
src/main/java/org/ligi/axt/converter/ImageFromIntentUriToFileConverter.java
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // }
import android.annotation.TargetApi; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.ligi.axt.AXT;
else id = wholeID; final String[] column = {MediaStore.Images.Media.DATA}; // where id is equal to final String sel = MediaStore.Images.Media._ID + "=?"; final Cursor innerCursor = context.getContentResolver(). query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{id}, null); final int columnIndex = innerCursor.getColumnIndex(column[0]); if (innerCursor.moveToFirst()) { return innerCursor.getString(columnIndex); } return null; } private File getBitmap(String tag, Uri url) { final File cacheDir = context.getCacheDir(); if (!cacheDir.exists()) { cacheDir.mkdirs(); } final File f = new File(cacheDir, tag); try { final InputStream is = getInputStreamByURL(url);
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // } // Path: src/main/java/org/ligi/axt/converter/ImageFromIntentUriToFileConverter.java import android.annotation.TargetApi; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.ligi.axt.AXT; else id = wholeID; final String[] column = {MediaStore.Images.Media.DATA}; // where id is equal to final String sel = MediaStore.Images.Media._ID + "=?"; final Cursor innerCursor = context.getContentResolver(). query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{id}, null); final int columnIndex = innerCursor.getColumnIndex(column[0]); if (innerCursor.moveToFirst()) { return innerCursor.getString(columnIndex); } return null; } private File getBitmap(String tag, Uri url) { final File cacheDir = context.getCacheDir(); if (!cacheDir.exists()) { cacheDir.mkdirs(); } final File f = new File(cacheDir, tag); try { final InputStream is = getInputStreamByURL(url);
AXT.at(is).toFile(f);
ligi/AXT
src/test/java/org/ligi/axt/test/TheInputStreamAXT.java
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // }
import android.os.Environment; import java.io.File; import java.io.IOException; import org.apache.tools.ant.filters.StringInputStream; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import static org.assertj.core.api.Assertions.assertThat;
package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheInputStreamAXT { private static final String STRING_PROBE = "first line\nsecond line"; private File ROOT = Environment.getExternalStorageDirectory(); @Test public void should_write_file_correctly() throws IOException { File file = new File(ROOT, "foo1");
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // } // Path: src/test/java/org/ligi/axt/test/TheInputStreamAXT.java import android.os.Environment; import java.io.File; import java.io.IOException; import org.apache.tools.ant.filters.StringInputStream; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import static org.assertj.core.api.Assertions.assertThat; package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheInputStreamAXT { private static final String STRING_PROBE = "first line\nsecond line"; private File ROOT = Environment.getExternalStorageDirectory(); @Test public void should_write_file_correctly() throws IOException { File file = new File(ROOT, "foo1");
AXT.at(new StringInputStream(STRING_PROBE)).toFile(file);
ligi/AXT
src/test/java/org/ligi/axt/test/TheFileAXT.java
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // }
import android.os.Environment; import java.io.File; import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat;
package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheFileAXT { private File EXT_DIR = Environment.getExternalStorageDirectory(); private String DEFAULT_DIR = "foo_dir "; @Test public void delete_recursive_should_behave_correct_when_no_dir_there() { File testDir = new File(EXT_DIR, DEFAULT_DIR); // should not exist assertThat(testDir.exists()).isEqualTo(false); // invoke and check return code
// Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // } // Path: src/test/java/org/ligi/axt/test/TheFileAXT.java import android.os.Environment; import java.io.File; import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat; package org.ligi.axt.test; @RunWith(RobolectricTestRunner.class) public class TheFileAXT { private File EXT_DIR = Environment.getExternalStorageDirectory(); private String DEFAULT_DIR = "foo_dir "; @Test public void delete_recursive_should_behave_correct_when_no_dir_there() { File testDir = new File(EXT_DIR, DEFAULT_DIR); // should not exist assertThat(testDir.exists()).isEqualTo(false); // invoke and check return code
assertThat(AXT.at(testDir).deleteRecursive()).isEqualTo(false);
ligi/AXT
src/test/java/org/ligi/axt/test/TheStringAXT.java
// Path: src/test/java/org/ligi/CustomRobolectricRunner.java // public class CustomRobolectricRunner extends RobolectricTestRunner { // public CustomRobolectricRunner(Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected AndroidManifest getAppManifest(Config config) { // String manifestPath = "AndroidManifest.xml"; // String resPath = "build/intermediates/res/" + BuildConfig.BUILD_TYPE; // // // android studio has a different execution root for tests than pure gradle // // so we avoid here manual effort to get them running inside android studio // if (!new File(manifestPath).exists()) { // manifestPath = "app/" + manifestPath; // } // // config = overwriteConfig(config, "manifest", manifestPath); // config = overwriteConfig(config, "resourceDir", resPath); // return super.getAppManifest(config); // } // // private Config.Implementation overwriteConfig(Config config, String key, String value) { // Properties properties = new Properties(); // properties.setProperty(key, value); // return new Config.Implementation(config, Config.Implementation.fromProperties(properties)); // } // // } // // Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // }
import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.CustomRobolectricRunner; import org.ligi.axt.AXT; import static org.assertj.core.api.Assertions.assertThat;
package org.ligi.axt.test; @RunWith(CustomRobolectricRunner.class) public class TheStringAXT { @Test public void should_parse_rgb_correct() {
// Path: src/test/java/org/ligi/CustomRobolectricRunner.java // public class CustomRobolectricRunner extends RobolectricTestRunner { // public CustomRobolectricRunner(Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected AndroidManifest getAppManifest(Config config) { // String manifestPath = "AndroidManifest.xml"; // String resPath = "build/intermediates/res/" + BuildConfig.BUILD_TYPE; // // // android studio has a different execution root for tests than pure gradle // // so we avoid here manual effort to get them running inside android studio // if (!new File(manifestPath).exists()) { // manifestPath = "app/" + manifestPath; // } // // config = overwriteConfig(config, "manifest", manifestPath); // config = overwriteConfig(config, "resourceDir", resPath); // return super.getAppManifest(config); // } // // private Config.Implementation overwriteConfig(Config config, String key, String value) { // Properties properties = new Properties(); // properties.setProperty(key, value); // return new Config.Implementation(config, Config.Implementation.fromProperties(properties)); // } // // } // // Path: src/main/java/org/ligi/axt/AXT.java // public class AXT { // public static CheckBoxAXT at(CheckBox checkBox) { // return new CheckBoxAXT(checkBox); // } // // public static BitmapAXT at(Bitmap bitmap) { // return new BitmapAXT(bitmap); // } // // public static ActivityAXT at(Activity activity) { // return new ActivityAXT(activity); // } // // public static FragmentAXT at(Fragment fragment) { // return new FragmentAXT(fragment); // } // // public static FileAXT at(File file) { // return new FileAXT(file); // } // // public static <T> ArrayAXT<T> at(T[] arr) { // return new ArrayAXT<T>(arr); // } // // public static IntentAXT at(Intent intent) { // return new IntentAXT(intent); // } // // public static URLAXT at(URL url) { // return new URLAXT(url); // } // // public static EditTextAXT at(EditText editText) { // return new EditTextAXT(editText); // } // // public static ContextAXT at(Context ctx) { // return new ContextAXT(ctx); // } // // public static InputStreamAXT at(InputStream inputStream) { // return new InputStreamAXT(inputStream); // } // // public static ViewAXT at(View view) { // return new ViewAXT(view); // } // // public static PaintAXT at(Paint paint) { // return new PaintAXT(paint); // } // // public static WindowManagerAXT at(WindowManager windowManager) { // return new WindowManagerAXT(windowManager); // } // // public static ResolveInfoAXT at(ResolveInfo resolveInfo) { // return new ResolveInfoAXT(resolveInfo); // } // // public static StringAXT at(String string) { // return new StringAXT(string); // } // // public static UriAXT at(Uri uri) { // return new UriAXT(uri); // } // } // Path: src/test/java/org/ligi/axt/test/TheStringAXT.java import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.CustomRobolectricRunner; import org.ligi.axt.AXT; import static org.assertj.core.api.Assertions.assertThat; package org.ligi.axt.test; @RunWith(CustomRobolectricRunner.class) public class TheStringAXT { @Test public void should_parse_rgb_correct() {
final int result = AXT.at("rgb(204,204,204)").parseColor(23);
ligi/AXT
src/main/java/org/ligi/axt/extensions/ContextAXT.java
// Path: src/main/java/org/ligi/axt/extensions/misc/CommonIntentStarter.java // public class CommonIntentStarter { // // public final Context context; // // defaults to true as a common pitfall is to forget FLAG_ACTIVITY_NEW_TASK when needed // private boolean asNewTask = true; // // public CommonIntentStarter(final Context context) { // this.context = context; // } // // public void openUrl(final String urlString) { // final Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse(urlString)); // start(intent); // } // // public void shareUrl(final String urlString) { // final Intent intent = new Intent(Intent.ACTION_SEND); // intent.putExtra(Intent.EXTRA_TEXT, urlString); // intent.setType("text/plain"); // startChooser(intent); // } // // public void activityFromClass(Class class2start) { // final Intent intent = new Intent(context, class2start); // start(intent); // } // // public CommonIntentStarter noNewTask() { // asNewTask = false; // return this; // } // // private void startChooser(final Intent intent) { // final Intent chooserIntent = Intent.createChooser(intent, null); // start(chooserIntent); // } // // private void start(Intent intent) { // if (asNewTask) { // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // } // context.startActivity(intent); // } // }
import android.content.Context; import android.view.ViewConfiguration; import java.lang.reflect.Field; import org.ligi.axt.extensions.misc.CommonIntentStarter;
package org.ligi.axt.extensions; public class ContextAXT { private final Context context; public ContextAXT(Context context) { this.context = context; } /** * a little hack because I strongly disagree with the style guide here * ;-) * not having the Actionbar overfow menu also with devices with hardware * key really helps discoverability * http://stackoverflow.com/questions/9286822/how-to-force-use-of-overflow-menu-on-devices-with-menu-button */ public void forceOverFlowMenuEvenThoughDeviceHasPhysical() { try { ViewConfiguration config = ViewConfiguration.get(context); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if (menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception ex) { // Ignore - but at least we tried ;-) } }
// Path: src/main/java/org/ligi/axt/extensions/misc/CommonIntentStarter.java // public class CommonIntentStarter { // // public final Context context; // // defaults to true as a common pitfall is to forget FLAG_ACTIVITY_NEW_TASK when needed // private boolean asNewTask = true; // // public CommonIntentStarter(final Context context) { // this.context = context; // } // // public void openUrl(final String urlString) { // final Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse(urlString)); // start(intent); // } // // public void shareUrl(final String urlString) { // final Intent intent = new Intent(Intent.ACTION_SEND); // intent.putExtra(Intent.EXTRA_TEXT, urlString); // intent.setType("text/plain"); // startChooser(intent); // } // // public void activityFromClass(Class class2start) { // final Intent intent = new Intent(context, class2start); // start(intent); // } // // public CommonIntentStarter noNewTask() { // asNewTask = false; // return this; // } // // private void startChooser(final Intent intent) { // final Intent chooserIntent = Intent.createChooser(intent, null); // start(chooserIntent); // } // // private void start(Intent intent) { // if (asNewTask) { // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // } // context.startActivity(intent); // } // } // Path: src/main/java/org/ligi/axt/extensions/ContextAXT.java import android.content.Context; import android.view.ViewConfiguration; import java.lang.reflect.Field; import org.ligi.axt.extensions.misc.CommonIntentStarter; package org.ligi.axt.extensions; public class ContextAXT { private final Context context; public ContextAXT(Context context) { this.context = context; } /** * a little hack because I strongly disagree with the style guide here * ;-) * not having the Actionbar overfow menu also with devices with hardware * key really helps discoverability * http://stackoverflow.com/questions/9286822/how-to-force-use-of-overflow-menu-on-devices-with-menu-button */ public void forceOverFlowMenuEvenThoughDeviceHasPhysical() { try { ViewConfiguration config = ViewConfiguration.get(context); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if (menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception ex) { // Ignore - but at least we tried ;-) } }
public CommonIntentStarter startCommonIntent() {
ryankennedy/swagger-jaxrs-doclet
jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/ServiceDoclet.java
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/parser/JaxRsAnnotationParser.java // public class JaxRsAnnotationParser { // // private final DocletOptions options; // private final RootDoc rootDoc; // // public JaxRsAnnotationParser(DocletOptions options, RootDoc rootDoc) { // this.options = options; // this.rootDoc = rootDoc; // } // // public boolean run() { // try { // Collection<ApiDeclaration> declarations = new ArrayList<ApiDeclaration>(); // for (ClassDoc classDoc : rootDoc.classes()) { // ApiClassParser classParser = new ApiClassParser(options, classDoc, Arrays.asList(rootDoc.classes())); // Collection<Api> apis = classParser.parse(); // if (apis.isEmpty()) { // continue; // } // // Map<String, Model> models = uniqueIndex(classParser.models(), new Function<Model, String>() { // @Override // public String apply(Model model) { // return model.getId(); // } // }); // // The idea (and need) for the declaration is that "/foo" and "/foo/annotated" are stored in separate // // Api classes but are part of the same resource. // declarations.add(new ApiDeclaration(options.getApiVersion(), options.getApiBasePath(), classParser.getRootPath(), apis, models)); // } // writeApis(declarations); // return true; // } catch (IOException e) { // return false; // } // } // // private void writeApis(Collection<ApiDeclaration> apis) throws IOException { // List<ResourceListingAPI> resources = new LinkedList<ResourceListingAPI>(); // File outputDirectory = options.getOutputDirectory(); // String swaggerUiZipPath = options.getSwaggerUiZipPath(); // Recorder recorder = options.getRecorder(); // for (ApiDeclaration api : apis) { // String resourcePath = api.getResourcePath(); // if (!Strings.isNullOrEmpty(resourcePath)) { // String resourceName = resourcePath.replaceFirst("/", "").replaceAll("/", "_").replaceAll("[\\{\\}]", ""); // resources.add(new ResourceListingAPI("/" + resourceName + ".{format}", "")); // File apiFile = new File(outputDirectory, resourceName + ".json"); // recorder.record(apiFile, api); // } // } // // //write out json for api // ResourceListing listing = new ResourceListing(options.getApiVersion(), options.getDocBasePath(), resources); // File docFile = new File(outputDirectory, "service.json"); // recorder.record(docFile, listing); // // // Copy swagger-ui into the output directory. // ZipInputStream swaggerZip; // if (DocletOptions.DEFAULT_SWAGGER_UI_ZIP_PATH.equals(swaggerUiZipPath)) { // swaggerZip = new ZipInputStream(ServiceDoclet.class.getResourceAsStream("/swagger-ui.zip")); // System.out.println("Using default swagger-ui.zip file from SwaggerDoclet jar file"); // } else { // if (new File(swaggerUiZipPath).exists()) { // swaggerZip = new ZipInputStream(new FileInputStream(swaggerUiZipPath)); // System.out.println("Using swagger-ui.zip file from: " + swaggerUiZipPath); // } else { // File f = new File("."); // System.out.println("SwaggerDoclet working directory: " + f.getAbsolutePath()); // System.out.println("-swaggerUiZipPath not set correct: " + swaggerUiZipPath); // // throw new RuntimeException("-swaggerUiZipPath not set correct, file not found: " + swaggerUiZipPath); // } // } // // ZipEntry entry = swaggerZip.getNextEntry(); // while (entry != null) { // final File swaggerFile = new File(outputDirectory, entry.getName()); // if (entry.isDirectory()) { // if (!swaggerFile.isDirectory() && !swaggerFile.mkdirs()) { // throw new RuntimeException("Unable to create directory: " + swaggerFile); // } // } else { // recorder.record(swaggerFile, swaggerZip); // } // // entry = swaggerZip.getNextEntry(); // } // swaggerZip.close(); // } // // }
import com.hypnoticocelot.jaxrs.doclet.parser.JaxRsAnnotationParser; import com.sun.javadoc.LanguageVersion; import com.sun.javadoc.RootDoc; import java.util.HashMap; import java.util.Map;
package com.hypnoticocelot.jaxrs.doclet; public class ServiceDoclet { /** * Generate documentation here. * This method is required for all doclets. * * @return true on success. */ public static boolean start(RootDoc doc) { DocletOptions options = DocletOptions.parse(doc.options());
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/parser/JaxRsAnnotationParser.java // public class JaxRsAnnotationParser { // // private final DocletOptions options; // private final RootDoc rootDoc; // // public JaxRsAnnotationParser(DocletOptions options, RootDoc rootDoc) { // this.options = options; // this.rootDoc = rootDoc; // } // // public boolean run() { // try { // Collection<ApiDeclaration> declarations = new ArrayList<ApiDeclaration>(); // for (ClassDoc classDoc : rootDoc.classes()) { // ApiClassParser classParser = new ApiClassParser(options, classDoc, Arrays.asList(rootDoc.classes())); // Collection<Api> apis = classParser.parse(); // if (apis.isEmpty()) { // continue; // } // // Map<String, Model> models = uniqueIndex(classParser.models(), new Function<Model, String>() { // @Override // public String apply(Model model) { // return model.getId(); // } // }); // // The idea (and need) for the declaration is that "/foo" and "/foo/annotated" are stored in separate // // Api classes but are part of the same resource. // declarations.add(new ApiDeclaration(options.getApiVersion(), options.getApiBasePath(), classParser.getRootPath(), apis, models)); // } // writeApis(declarations); // return true; // } catch (IOException e) { // return false; // } // } // // private void writeApis(Collection<ApiDeclaration> apis) throws IOException { // List<ResourceListingAPI> resources = new LinkedList<ResourceListingAPI>(); // File outputDirectory = options.getOutputDirectory(); // String swaggerUiZipPath = options.getSwaggerUiZipPath(); // Recorder recorder = options.getRecorder(); // for (ApiDeclaration api : apis) { // String resourcePath = api.getResourcePath(); // if (!Strings.isNullOrEmpty(resourcePath)) { // String resourceName = resourcePath.replaceFirst("/", "").replaceAll("/", "_").replaceAll("[\\{\\}]", ""); // resources.add(new ResourceListingAPI("/" + resourceName + ".{format}", "")); // File apiFile = new File(outputDirectory, resourceName + ".json"); // recorder.record(apiFile, api); // } // } // // //write out json for api // ResourceListing listing = new ResourceListing(options.getApiVersion(), options.getDocBasePath(), resources); // File docFile = new File(outputDirectory, "service.json"); // recorder.record(docFile, listing); // // // Copy swagger-ui into the output directory. // ZipInputStream swaggerZip; // if (DocletOptions.DEFAULT_SWAGGER_UI_ZIP_PATH.equals(swaggerUiZipPath)) { // swaggerZip = new ZipInputStream(ServiceDoclet.class.getResourceAsStream("/swagger-ui.zip")); // System.out.println("Using default swagger-ui.zip file from SwaggerDoclet jar file"); // } else { // if (new File(swaggerUiZipPath).exists()) { // swaggerZip = new ZipInputStream(new FileInputStream(swaggerUiZipPath)); // System.out.println("Using swagger-ui.zip file from: " + swaggerUiZipPath); // } else { // File f = new File("."); // System.out.println("SwaggerDoclet working directory: " + f.getAbsolutePath()); // System.out.println("-swaggerUiZipPath not set correct: " + swaggerUiZipPath); // // throw new RuntimeException("-swaggerUiZipPath not set correct, file not found: " + swaggerUiZipPath); // } // } // // ZipEntry entry = swaggerZip.getNextEntry(); // while (entry != null) { // final File swaggerFile = new File(outputDirectory, entry.getName()); // if (entry.isDirectory()) { // if (!swaggerFile.isDirectory() && !swaggerFile.mkdirs()) { // throw new RuntimeException("Unable to create directory: " + swaggerFile); // } // } else { // recorder.record(swaggerFile, swaggerZip); // } // // entry = swaggerZip.getNextEntry(); // } // swaggerZip.close(); // } // // } // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/ServiceDoclet.java import com.hypnoticocelot.jaxrs.doclet.parser.JaxRsAnnotationParser; import com.sun.javadoc.LanguageVersion; import com.sun.javadoc.RootDoc; import java.util.HashMap; import java.util.Map; package com.hypnoticocelot.jaxrs.doclet; public class ServiceDoclet { /** * Generate documentation here. * This method is required for all doclets. * * @return true on success. */ public static boolean start(RootDoc doc) { DocletOptions options = DocletOptions.parse(doc.options());
return new JaxRsAnnotationParser(options, doc).run();
ryankennedy/swagger-jaxrs-doclet
jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/Recorder.java
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ApiDeclaration.java // @JsonPropertyOrder({"apiVersion", "swaggerVersion", "basePath", "resourcePath", "apis", "models"}) // public class ApiDeclaration { // private String apiVersion; // private String swaggerVersion; // private String basePath; // private String resourcePath; // private Collection<Api> apis; // private Map<String, Model> models; // // @SuppressWarnings("unused") // private ApiDeclaration() { // } // // public ApiDeclaration(String apiVersion, String basePath, String resourcePath, Collection<Api> apis, Map<String, Model> models) { // this.apiVersion = apiVersion; // this.swaggerVersion = "1.1"; // this.basePath = basePath; // this.resourcePath = resourcePath; // this.apis = apis.isEmpty() ? null : apis; // this.models = models.isEmpty() ? null : models; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return swaggerVersion; // } // // public String getBasePath() { // return basePath; // } // // public String getResourcePath() { // return resourcePath; // } // // public Collection<Api> getApis() { // return apis; // } // // public Map<String, Model> getModels() { // return models; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApiDeclaration that = (ApiDeclaration) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(swaggerVersion, that.swaggerVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(resourcePath, that.resourcePath) // && Objects.equal(apis, that.apis) // && Objects.equal(models, that.models); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, swaggerVersion, basePath, resourcePath, apis, models); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("swaggerVersion", swaggerVersion) // .add("basePath", basePath) // .add("resourcePath", resourcePath) // .add("apis", apis) // .add("models", models) // .toString(); // } // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ResourceListing.java // public class ResourceListing { // private String apiVersion; // private String basePath; // private List<ResourceListingAPI> apis; // // @SuppressWarnings("unused") // private ResourceListing() { // } // // public ResourceListing(String apiVersion, String basePath, List<ResourceListingAPI> apis) { // this.apiVersion = apiVersion; // this.basePath = basePath; // this.apis = apis; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return "1.1"; // } // // public String getBasePath() { // return basePath; // } // // public List<ResourceListingAPI> getApis() { // return apis; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ResourceListing that = (ResourceListing) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(apis, that.apis); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, basePath, apis); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("basePath", basePath) // .add("apis", apis) // .toString(); // } // }
import com.hypnoticocelot.jaxrs.doclet.model.ApiDeclaration; import com.hypnoticocelot.jaxrs.doclet.model.ResourceListing; import java.io.File; import java.io.IOException; import java.io.InputStream;
package com.hypnoticocelot.jaxrs.doclet; public interface Recorder { void record(File file, ResourceListing listing) throws IOException;
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ApiDeclaration.java // @JsonPropertyOrder({"apiVersion", "swaggerVersion", "basePath", "resourcePath", "apis", "models"}) // public class ApiDeclaration { // private String apiVersion; // private String swaggerVersion; // private String basePath; // private String resourcePath; // private Collection<Api> apis; // private Map<String, Model> models; // // @SuppressWarnings("unused") // private ApiDeclaration() { // } // // public ApiDeclaration(String apiVersion, String basePath, String resourcePath, Collection<Api> apis, Map<String, Model> models) { // this.apiVersion = apiVersion; // this.swaggerVersion = "1.1"; // this.basePath = basePath; // this.resourcePath = resourcePath; // this.apis = apis.isEmpty() ? null : apis; // this.models = models.isEmpty() ? null : models; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return swaggerVersion; // } // // public String getBasePath() { // return basePath; // } // // public String getResourcePath() { // return resourcePath; // } // // public Collection<Api> getApis() { // return apis; // } // // public Map<String, Model> getModels() { // return models; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApiDeclaration that = (ApiDeclaration) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(swaggerVersion, that.swaggerVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(resourcePath, that.resourcePath) // && Objects.equal(apis, that.apis) // && Objects.equal(models, that.models); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, swaggerVersion, basePath, resourcePath, apis, models); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("swaggerVersion", swaggerVersion) // .add("basePath", basePath) // .add("resourcePath", resourcePath) // .add("apis", apis) // .add("models", models) // .toString(); // } // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ResourceListing.java // public class ResourceListing { // private String apiVersion; // private String basePath; // private List<ResourceListingAPI> apis; // // @SuppressWarnings("unused") // private ResourceListing() { // } // // public ResourceListing(String apiVersion, String basePath, List<ResourceListingAPI> apis) { // this.apiVersion = apiVersion; // this.basePath = basePath; // this.apis = apis; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return "1.1"; // } // // public String getBasePath() { // return basePath; // } // // public List<ResourceListingAPI> getApis() { // return apis; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ResourceListing that = (ResourceListing) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(apis, that.apis); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, basePath, apis); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("basePath", basePath) // .add("apis", apis) // .toString(); // } // } // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/Recorder.java import com.hypnoticocelot.jaxrs.doclet.model.ApiDeclaration; import com.hypnoticocelot.jaxrs.doclet.model.ResourceListing; import java.io.File; import java.io.IOException; import java.io.InputStream; package com.hypnoticocelot.jaxrs.doclet; public interface Recorder { void record(File file, ResourceListing listing) throws IOException;
void record(File file, ApiDeclaration declaration) throws IOException;
ryankennedy/swagger-jaxrs-doclet
jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/Operation.java
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/parser/AnnotationHelper.java // public class AnnotationHelper { // // private static final String JAX_RS_ANNOTATION_PACKAGE = "javax.ws.rs"; // private static final String JAX_RS_PATH = "javax.ws.rs.Path"; // private static final String JAX_RS_PATH_PARAM = "javax.ws.rs.PathParam"; // private static final String JAX_RS_QUERY_PARAM = "javax.ws.rs.QueryParam"; // private static final String JERSEY_MULTIPART_FORM_PARAM = "com.sun.jersey.multipart.FormDataParam"; // // @SuppressWarnings("serial") // static final List<String> PRIMITIVES = new ArrayList<String>() {{ // add("byte"); // add("boolean"); // add("int"); // add("long"); // add("float"); // add("double"); // add("string"); // add("Date"); // }}; // // public static String parsePath(AnnotationDesc[] annotations) { // for (AnnotationDesc annotationDesc : annotations) { // if (annotationDesc.annotationType().qualifiedTypeName().equals(JAX_RS_PATH)) { // for (AnnotationDesc.ElementValuePair pair : annotationDesc.elementValues()) { // if (pair.element().name().equals("value")) { // String path = pair.value().value().toString(); // if (path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // return path.isEmpty() || path.startsWith("/") ? path : "/" + path; // } // } // } // } // return null; // } // // /** // * Determines the String representation of the object Type. // */ // public static String typeOf(String javaType) { // String type; // if (javaType.startsWith("java.lang.")) { // int i = javaType.lastIndexOf("."); // type = javaType.substring(i + 1).toLowerCase(); // } else if (PRIMITIVES.contains(javaType.toLowerCase())) { // type = javaType.toLowerCase(); // } else if (javaType.equals("java.util.Date")) { // type = "Date"; // } else { // int i = javaType.lastIndexOf("."); // if (i >= 0) { // type = javaType.substring(i + 1); // } else { // type = javaType; // } // } // if (type.equalsIgnoreCase("integer")) { // type = "int"; // } else if (type.equalsIgnoreCase("arraylist") || type.equalsIgnoreCase("linkedlist")) { // type = "List"; // } // return type; // } // // /** // * Determines the string representation of the parameter type. // */ // public static String paramTypeOf(Parameter parameter) { // AnnotationParser p = new AnnotationParser(parameter); // if (p.isAnnotatedBy(JAX_RS_PATH_PARAM)) { // return "path"; // } else if (p.isAnnotatedBy(JAX_RS_QUERY_PARAM)) { // return "query"; // } else if(p.isAnnotatedBy(JERSEY_MULTIPART_FORM_PARAM)) { // return "form"; // } // return "body"; // } // // /** // * Determines the string representation of the parameter name. // */ // public static String paramNameOf(Parameter parameter) { // // TODO (DL): make this part of Translator? // AnnotationParser p = new AnnotationParser(parameter); // String name = p.getAnnotationValue(JAX_RS_PATH_PARAM, "value"); // if (name == null) { // name = p.getAnnotationValue(JAX_RS_QUERY_PARAM, "value"); // } // if (name == null) { // name = parameter.name(); // } // return name; // } // // public static boolean isPrimitive(Type type) { // return PRIMITIVES.contains(typeOf(type.qualifiedTypeName())); // } // // public static class ExcludedAnnotations implements Predicate<AnnotationDesc> { // private final DocletOptions options; // // public ExcludedAnnotations(DocletOptions options) { // this.options = options; // } // // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return options.getExcludeAnnotationClasses().contains(annotationClass); // } // } // // public static class JaxRsAnnotations implements Predicate<AnnotationDesc> { // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return annotationClass.startsWith(JAX_RS_ANNOTATION_PACKAGE); // } // } // // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Objects; import com.hypnoticocelot.jaxrs.doclet.parser.AnnotationHelper; import java.util.List; import static com.google.common.base.Strings.emptyToNull;
package com.hypnoticocelot.jaxrs.doclet.model; public class Operation { private HttpMethod httpMethod; private String nickname; private String responseClass; // void, primitive, complex or a container private List<ApiParameter> parameters; private String summary; // cap at 60 characters for readability in the UI private String notes; @JsonProperty("errorResponses") // swagger 1.1 name private List<ApiResponseMessage> responseMessages; // swagger 1.2 name @SuppressWarnings("unused") private Operation() { } public Operation(Method method) { this.httpMethod = method.getMethod(); this.nickname = emptyToNull(method.getMethodName());
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/parser/AnnotationHelper.java // public class AnnotationHelper { // // private static final String JAX_RS_ANNOTATION_PACKAGE = "javax.ws.rs"; // private static final String JAX_RS_PATH = "javax.ws.rs.Path"; // private static final String JAX_RS_PATH_PARAM = "javax.ws.rs.PathParam"; // private static final String JAX_RS_QUERY_PARAM = "javax.ws.rs.QueryParam"; // private static final String JERSEY_MULTIPART_FORM_PARAM = "com.sun.jersey.multipart.FormDataParam"; // // @SuppressWarnings("serial") // static final List<String> PRIMITIVES = new ArrayList<String>() {{ // add("byte"); // add("boolean"); // add("int"); // add("long"); // add("float"); // add("double"); // add("string"); // add("Date"); // }}; // // public static String parsePath(AnnotationDesc[] annotations) { // for (AnnotationDesc annotationDesc : annotations) { // if (annotationDesc.annotationType().qualifiedTypeName().equals(JAX_RS_PATH)) { // for (AnnotationDesc.ElementValuePair pair : annotationDesc.elementValues()) { // if (pair.element().name().equals("value")) { // String path = pair.value().value().toString(); // if (path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // return path.isEmpty() || path.startsWith("/") ? path : "/" + path; // } // } // } // } // return null; // } // // /** // * Determines the String representation of the object Type. // */ // public static String typeOf(String javaType) { // String type; // if (javaType.startsWith("java.lang.")) { // int i = javaType.lastIndexOf("."); // type = javaType.substring(i + 1).toLowerCase(); // } else if (PRIMITIVES.contains(javaType.toLowerCase())) { // type = javaType.toLowerCase(); // } else if (javaType.equals("java.util.Date")) { // type = "Date"; // } else { // int i = javaType.lastIndexOf("."); // if (i >= 0) { // type = javaType.substring(i + 1); // } else { // type = javaType; // } // } // if (type.equalsIgnoreCase("integer")) { // type = "int"; // } else if (type.equalsIgnoreCase("arraylist") || type.equalsIgnoreCase("linkedlist")) { // type = "List"; // } // return type; // } // // /** // * Determines the string representation of the parameter type. // */ // public static String paramTypeOf(Parameter parameter) { // AnnotationParser p = new AnnotationParser(parameter); // if (p.isAnnotatedBy(JAX_RS_PATH_PARAM)) { // return "path"; // } else if (p.isAnnotatedBy(JAX_RS_QUERY_PARAM)) { // return "query"; // } else if(p.isAnnotatedBy(JERSEY_MULTIPART_FORM_PARAM)) { // return "form"; // } // return "body"; // } // // /** // * Determines the string representation of the parameter name. // */ // public static String paramNameOf(Parameter parameter) { // // TODO (DL): make this part of Translator? // AnnotationParser p = new AnnotationParser(parameter); // String name = p.getAnnotationValue(JAX_RS_PATH_PARAM, "value"); // if (name == null) { // name = p.getAnnotationValue(JAX_RS_QUERY_PARAM, "value"); // } // if (name == null) { // name = parameter.name(); // } // return name; // } // // public static boolean isPrimitive(Type type) { // return PRIMITIVES.contains(typeOf(type.qualifiedTypeName())); // } // // public static class ExcludedAnnotations implements Predicate<AnnotationDesc> { // private final DocletOptions options; // // public ExcludedAnnotations(DocletOptions options) { // this.options = options; // } // // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return options.getExcludeAnnotationClasses().contains(annotationClass); // } // } // // public static class JaxRsAnnotations implements Predicate<AnnotationDesc> { // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return annotationClass.startsWith(JAX_RS_ANNOTATION_PACKAGE); // } // } // // } // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/Operation.java import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Objects; import com.hypnoticocelot.jaxrs.doclet.parser.AnnotationHelper; import java.util.List; import static com.google.common.base.Strings.emptyToNull; package com.hypnoticocelot.jaxrs.doclet.model; public class Operation { private HttpMethod httpMethod; private String nickname; private String responseClass; // void, primitive, complex or a container private List<ApiParameter> parameters; private String summary; // cap at 60 characters for readability in the UI private String notes; @JsonProperty("errorResponses") // swagger 1.1 name private List<ApiResponseMessage> responseMessages; // swagger 1.2 name @SuppressWarnings("unused") private Operation() { } public Operation(Method method) { this.httpMethod = method.getMethod(); this.nickname = emptyToNull(method.getMethodName());
this.responseClass = emptyToNull(AnnotationHelper.typeOf(method.getReturnType()));
ryankennedy/swagger-jaxrs-doclet
jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/NameBasedTranslator.java
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/parser/AnnotationHelper.java // public class AnnotationHelper { // // private static final String JAX_RS_ANNOTATION_PACKAGE = "javax.ws.rs"; // private static final String JAX_RS_PATH = "javax.ws.rs.Path"; // private static final String JAX_RS_PATH_PARAM = "javax.ws.rs.PathParam"; // private static final String JAX_RS_QUERY_PARAM = "javax.ws.rs.QueryParam"; // private static final String JERSEY_MULTIPART_FORM_PARAM = "com.sun.jersey.multipart.FormDataParam"; // // @SuppressWarnings("serial") // static final List<String> PRIMITIVES = new ArrayList<String>() {{ // add("byte"); // add("boolean"); // add("int"); // add("long"); // add("float"); // add("double"); // add("string"); // add("Date"); // }}; // // public static String parsePath(AnnotationDesc[] annotations) { // for (AnnotationDesc annotationDesc : annotations) { // if (annotationDesc.annotationType().qualifiedTypeName().equals(JAX_RS_PATH)) { // for (AnnotationDesc.ElementValuePair pair : annotationDesc.elementValues()) { // if (pair.element().name().equals("value")) { // String path = pair.value().value().toString(); // if (path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // return path.isEmpty() || path.startsWith("/") ? path : "/" + path; // } // } // } // } // return null; // } // // /** // * Determines the String representation of the object Type. // */ // public static String typeOf(String javaType) { // String type; // if (javaType.startsWith("java.lang.")) { // int i = javaType.lastIndexOf("."); // type = javaType.substring(i + 1).toLowerCase(); // } else if (PRIMITIVES.contains(javaType.toLowerCase())) { // type = javaType.toLowerCase(); // } else if (javaType.equals("java.util.Date")) { // type = "Date"; // } else { // int i = javaType.lastIndexOf("."); // if (i >= 0) { // type = javaType.substring(i + 1); // } else { // type = javaType; // } // } // if (type.equalsIgnoreCase("integer")) { // type = "int"; // } else if (type.equalsIgnoreCase("arraylist") || type.equalsIgnoreCase("linkedlist")) { // type = "List"; // } // return type; // } // // /** // * Determines the string representation of the parameter type. // */ // public static String paramTypeOf(Parameter parameter) { // AnnotationParser p = new AnnotationParser(parameter); // if (p.isAnnotatedBy(JAX_RS_PATH_PARAM)) { // return "path"; // } else if (p.isAnnotatedBy(JAX_RS_QUERY_PARAM)) { // return "query"; // } else if(p.isAnnotatedBy(JERSEY_MULTIPART_FORM_PARAM)) { // return "form"; // } // return "body"; // } // // /** // * Determines the string representation of the parameter name. // */ // public static String paramNameOf(Parameter parameter) { // // TODO (DL): make this part of Translator? // AnnotationParser p = new AnnotationParser(parameter); // String name = p.getAnnotationValue(JAX_RS_PATH_PARAM, "value"); // if (name == null) { // name = p.getAnnotationValue(JAX_RS_QUERY_PARAM, "value"); // } // if (name == null) { // name = parameter.name(); // } // return name; // } // // public static boolean isPrimitive(Type type) { // return PRIMITIVES.contains(typeOf(type.qualifiedTypeName())); // } // // public static class ExcludedAnnotations implements Predicate<AnnotationDesc> { // private final DocletOptions options; // // public ExcludedAnnotations(DocletOptions options) { // this.options = options; // } // // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return options.getExcludeAnnotationClasses().contains(annotationClass); // } // } // // public static class JaxRsAnnotations implements Predicate<AnnotationDesc> { // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return annotationClass.startsWith(JAX_RS_ANNOTATION_PACKAGE); // } // } // // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/Translator.java // public static OptionalName presentOrMissing(String name) { // if (!Strings.isNullOrEmpty(name)) { // return new OptionalName(Status.PRESENT, name); // } else { // return new OptionalName(Status.MISSING, null); // } // }
import com.hypnoticocelot.jaxrs.doclet.parser.AnnotationHelper; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.MethodDoc; import com.sun.javadoc.Type; import static com.hypnoticocelot.jaxrs.doclet.translator.Translator.OptionalName.presentOrMissing;
package com.hypnoticocelot.jaxrs.doclet.translator; public class NameBasedTranslator implements Translator { @Override public OptionalName typeName(Type type) {
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/parser/AnnotationHelper.java // public class AnnotationHelper { // // private static final String JAX_RS_ANNOTATION_PACKAGE = "javax.ws.rs"; // private static final String JAX_RS_PATH = "javax.ws.rs.Path"; // private static final String JAX_RS_PATH_PARAM = "javax.ws.rs.PathParam"; // private static final String JAX_RS_QUERY_PARAM = "javax.ws.rs.QueryParam"; // private static final String JERSEY_MULTIPART_FORM_PARAM = "com.sun.jersey.multipart.FormDataParam"; // // @SuppressWarnings("serial") // static final List<String> PRIMITIVES = new ArrayList<String>() {{ // add("byte"); // add("boolean"); // add("int"); // add("long"); // add("float"); // add("double"); // add("string"); // add("Date"); // }}; // // public static String parsePath(AnnotationDesc[] annotations) { // for (AnnotationDesc annotationDesc : annotations) { // if (annotationDesc.annotationType().qualifiedTypeName().equals(JAX_RS_PATH)) { // for (AnnotationDesc.ElementValuePair pair : annotationDesc.elementValues()) { // if (pair.element().name().equals("value")) { // String path = pair.value().value().toString(); // if (path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // return path.isEmpty() || path.startsWith("/") ? path : "/" + path; // } // } // } // } // return null; // } // // /** // * Determines the String representation of the object Type. // */ // public static String typeOf(String javaType) { // String type; // if (javaType.startsWith("java.lang.")) { // int i = javaType.lastIndexOf("."); // type = javaType.substring(i + 1).toLowerCase(); // } else if (PRIMITIVES.contains(javaType.toLowerCase())) { // type = javaType.toLowerCase(); // } else if (javaType.equals("java.util.Date")) { // type = "Date"; // } else { // int i = javaType.lastIndexOf("."); // if (i >= 0) { // type = javaType.substring(i + 1); // } else { // type = javaType; // } // } // if (type.equalsIgnoreCase("integer")) { // type = "int"; // } else if (type.equalsIgnoreCase("arraylist") || type.equalsIgnoreCase("linkedlist")) { // type = "List"; // } // return type; // } // // /** // * Determines the string representation of the parameter type. // */ // public static String paramTypeOf(Parameter parameter) { // AnnotationParser p = new AnnotationParser(parameter); // if (p.isAnnotatedBy(JAX_RS_PATH_PARAM)) { // return "path"; // } else if (p.isAnnotatedBy(JAX_RS_QUERY_PARAM)) { // return "query"; // } else if(p.isAnnotatedBy(JERSEY_MULTIPART_FORM_PARAM)) { // return "form"; // } // return "body"; // } // // /** // * Determines the string representation of the parameter name. // */ // public static String paramNameOf(Parameter parameter) { // // TODO (DL): make this part of Translator? // AnnotationParser p = new AnnotationParser(parameter); // String name = p.getAnnotationValue(JAX_RS_PATH_PARAM, "value"); // if (name == null) { // name = p.getAnnotationValue(JAX_RS_QUERY_PARAM, "value"); // } // if (name == null) { // name = parameter.name(); // } // return name; // } // // public static boolean isPrimitive(Type type) { // return PRIMITIVES.contains(typeOf(type.qualifiedTypeName())); // } // // public static class ExcludedAnnotations implements Predicate<AnnotationDesc> { // private final DocletOptions options; // // public ExcludedAnnotations(DocletOptions options) { // this.options = options; // } // // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return options.getExcludeAnnotationClasses().contains(annotationClass); // } // } // // public static class JaxRsAnnotations implements Predicate<AnnotationDesc> { // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return annotationClass.startsWith(JAX_RS_ANNOTATION_PACKAGE); // } // } // // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/Translator.java // public static OptionalName presentOrMissing(String name) { // if (!Strings.isNullOrEmpty(name)) { // return new OptionalName(Status.PRESENT, name); // } else { // return new OptionalName(Status.MISSING, null); // } // } // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/NameBasedTranslator.java import com.hypnoticocelot.jaxrs.doclet.parser.AnnotationHelper; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.MethodDoc; import com.sun.javadoc.Type; import static com.hypnoticocelot.jaxrs.doclet.translator.Translator.OptionalName.presentOrMissing; package com.hypnoticocelot.jaxrs.doclet.translator; public class NameBasedTranslator implements Translator { @Override public OptionalName typeName(Type type) {
return presentOrMissing(AnnotationHelper.typeOf(type.qualifiedTypeName()));
ryankennedy/swagger-jaxrs-doclet
jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/NameBasedTranslator.java
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/parser/AnnotationHelper.java // public class AnnotationHelper { // // private static final String JAX_RS_ANNOTATION_PACKAGE = "javax.ws.rs"; // private static final String JAX_RS_PATH = "javax.ws.rs.Path"; // private static final String JAX_RS_PATH_PARAM = "javax.ws.rs.PathParam"; // private static final String JAX_RS_QUERY_PARAM = "javax.ws.rs.QueryParam"; // private static final String JERSEY_MULTIPART_FORM_PARAM = "com.sun.jersey.multipart.FormDataParam"; // // @SuppressWarnings("serial") // static final List<String> PRIMITIVES = new ArrayList<String>() {{ // add("byte"); // add("boolean"); // add("int"); // add("long"); // add("float"); // add("double"); // add("string"); // add("Date"); // }}; // // public static String parsePath(AnnotationDesc[] annotations) { // for (AnnotationDesc annotationDesc : annotations) { // if (annotationDesc.annotationType().qualifiedTypeName().equals(JAX_RS_PATH)) { // for (AnnotationDesc.ElementValuePair pair : annotationDesc.elementValues()) { // if (pair.element().name().equals("value")) { // String path = pair.value().value().toString(); // if (path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // return path.isEmpty() || path.startsWith("/") ? path : "/" + path; // } // } // } // } // return null; // } // // /** // * Determines the String representation of the object Type. // */ // public static String typeOf(String javaType) { // String type; // if (javaType.startsWith("java.lang.")) { // int i = javaType.lastIndexOf("."); // type = javaType.substring(i + 1).toLowerCase(); // } else if (PRIMITIVES.contains(javaType.toLowerCase())) { // type = javaType.toLowerCase(); // } else if (javaType.equals("java.util.Date")) { // type = "Date"; // } else { // int i = javaType.lastIndexOf("."); // if (i >= 0) { // type = javaType.substring(i + 1); // } else { // type = javaType; // } // } // if (type.equalsIgnoreCase("integer")) { // type = "int"; // } else if (type.equalsIgnoreCase("arraylist") || type.equalsIgnoreCase("linkedlist")) { // type = "List"; // } // return type; // } // // /** // * Determines the string representation of the parameter type. // */ // public static String paramTypeOf(Parameter parameter) { // AnnotationParser p = new AnnotationParser(parameter); // if (p.isAnnotatedBy(JAX_RS_PATH_PARAM)) { // return "path"; // } else if (p.isAnnotatedBy(JAX_RS_QUERY_PARAM)) { // return "query"; // } else if(p.isAnnotatedBy(JERSEY_MULTIPART_FORM_PARAM)) { // return "form"; // } // return "body"; // } // // /** // * Determines the string representation of the parameter name. // */ // public static String paramNameOf(Parameter parameter) { // // TODO (DL): make this part of Translator? // AnnotationParser p = new AnnotationParser(parameter); // String name = p.getAnnotationValue(JAX_RS_PATH_PARAM, "value"); // if (name == null) { // name = p.getAnnotationValue(JAX_RS_QUERY_PARAM, "value"); // } // if (name == null) { // name = parameter.name(); // } // return name; // } // // public static boolean isPrimitive(Type type) { // return PRIMITIVES.contains(typeOf(type.qualifiedTypeName())); // } // // public static class ExcludedAnnotations implements Predicate<AnnotationDesc> { // private final DocletOptions options; // // public ExcludedAnnotations(DocletOptions options) { // this.options = options; // } // // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return options.getExcludeAnnotationClasses().contains(annotationClass); // } // } // // public static class JaxRsAnnotations implements Predicate<AnnotationDesc> { // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return annotationClass.startsWith(JAX_RS_ANNOTATION_PACKAGE); // } // } // // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/Translator.java // public static OptionalName presentOrMissing(String name) { // if (!Strings.isNullOrEmpty(name)) { // return new OptionalName(Status.PRESENT, name); // } else { // return new OptionalName(Status.MISSING, null); // } // }
import com.hypnoticocelot.jaxrs.doclet.parser.AnnotationHelper; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.MethodDoc; import com.sun.javadoc.Type; import static com.hypnoticocelot.jaxrs.doclet.translator.Translator.OptionalName.presentOrMissing;
package com.hypnoticocelot.jaxrs.doclet.translator; public class NameBasedTranslator implements Translator { @Override public OptionalName typeName(Type type) {
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/parser/AnnotationHelper.java // public class AnnotationHelper { // // private static final String JAX_RS_ANNOTATION_PACKAGE = "javax.ws.rs"; // private static final String JAX_RS_PATH = "javax.ws.rs.Path"; // private static final String JAX_RS_PATH_PARAM = "javax.ws.rs.PathParam"; // private static final String JAX_RS_QUERY_PARAM = "javax.ws.rs.QueryParam"; // private static final String JERSEY_MULTIPART_FORM_PARAM = "com.sun.jersey.multipart.FormDataParam"; // // @SuppressWarnings("serial") // static final List<String> PRIMITIVES = new ArrayList<String>() {{ // add("byte"); // add("boolean"); // add("int"); // add("long"); // add("float"); // add("double"); // add("string"); // add("Date"); // }}; // // public static String parsePath(AnnotationDesc[] annotations) { // for (AnnotationDesc annotationDesc : annotations) { // if (annotationDesc.annotationType().qualifiedTypeName().equals(JAX_RS_PATH)) { // for (AnnotationDesc.ElementValuePair pair : annotationDesc.elementValues()) { // if (pair.element().name().equals("value")) { // String path = pair.value().value().toString(); // if (path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // return path.isEmpty() || path.startsWith("/") ? path : "/" + path; // } // } // } // } // return null; // } // // /** // * Determines the String representation of the object Type. // */ // public static String typeOf(String javaType) { // String type; // if (javaType.startsWith("java.lang.")) { // int i = javaType.lastIndexOf("."); // type = javaType.substring(i + 1).toLowerCase(); // } else if (PRIMITIVES.contains(javaType.toLowerCase())) { // type = javaType.toLowerCase(); // } else if (javaType.equals("java.util.Date")) { // type = "Date"; // } else { // int i = javaType.lastIndexOf("."); // if (i >= 0) { // type = javaType.substring(i + 1); // } else { // type = javaType; // } // } // if (type.equalsIgnoreCase("integer")) { // type = "int"; // } else if (type.equalsIgnoreCase("arraylist") || type.equalsIgnoreCase("linkedlist")) { // type = "List"; // } // return type; // } // // /** // * Determines the string representation of the parameter type. // */ // public static String paramTypeOf(Parameter parameter) { // AnnotationParser p = new AnnotationParser(parameter); // if (p.isAnnotatedBy(JAX_RS_PATH_PARAM)) { // return "path"; // } else if (p.isAnnotatedBy(JAX_RS_QUERY_PARAM)) { // return "query"; // } else if(p.isAnnotatedBy(JERSEY_MULTIPART_FORM_PARAM)) { // return "form"; // } // return "body"; // } // // /** // * Determines the string representation of the parameter name. // */ // public static String paramNameOf(Parameter parameter) { // // TODO (DL): make this part of Translator? // AnnotationParser p = new AnnotationParser(parameter); // String name = p.getAnnotationValue(JAX_RS_PATH_PARAM, "value"); // if (name == null) { // name = p.getAnnotationValue(JAX_RS_QUERY_PARAM, "value"); // } // if (name == null) { // name = parameter.name(); // } // return name; // } // // public static boolean isPrimitive(Type type) { // return PRIMITIVES.contains(typeOf(type.qualifiedTypeName())); // } // // public static class ExcludedAnnotations implements Predicate<AnnotationDesc> { // private final DocletOptions options; // // public ExcludedAnnotations(DocletOptions options) { // this.options = options; // } // // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return options.getExcludeAnnotationClasses().contains(annotationClass); // } // } // // public static class JaxRsAnnotations implements Predicate<AnnotationDesc> { // @Override // public boolean apply(AnnotationDesc annotationDesc) { // String annotationClass = annotationDesc.annotationType().qualifiedTypeName(); // return annotationClass.startsWith(JAX_RS_ANNOTATION_PACKAGE); // } // } // // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/Translator.java // public static OptionalName presentOrMissing(String name) { // if (!Strings.isNullOrEmpty(name)) { // return new OptionalName(Status.PRESENT, name); // } else { // return new OptionalName(Status.MISSING, null); // } // } // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/NameBasedTranslator.java import com.hypnoticocelot.jaxrs.doclet.parser.AnnotationHelper; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.MethodDoc; import com.sun.javadoc.Type; import static com.hypnoticocelot.jaxrs.doclet.translator.Translator.OptionalName.presentOrMissing; package com.hypnoticocelot.jaxrs.doclet.translator; public class NameBasedTranslator implements Translator { @Override public OptionalName typeName(Type type) {
return presentOrMissing(AnnotationHelper.typeOf(type.qualifiedTypeName()));
ryankennedy/swagger-jaxrs-doclet
jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/resources/RecursiveResource.java
// Path: jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/api/Recursive.java // public class Recursive { // // private Recursive recursive; // // public Recursive getRecursive() { // return recursive; // } // // public void setRecursive(Recursive recursive) { // this.recursive = recursive; // } // // }
import com.hypnoticocelot.jaxrs.doclet.sample.api.Recursive; import javax.ws.rs.POST; import javax.ws.rs.Path;
package com.hypnoticocelot.jaxrs.doclet.sample.resources; @Path("/Recursive") public class RecursiveResource { @POST
// Path: jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/api/Recursive.java // public class Recursive { // // private Recursive recursive; // // public Recursive getRecursive() { // return recursive; // } // // public void setRecursive(Recursive recursive) { // this.recursive = recursive; // } // // } // Path: jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/resources/RecursiveResource.java import com.hypnoticocelot.jaxrs.doclet.sample.api.Recursive; import javax.ws.rs.POST; import javax.ws.rs.Path; package com.hypnoticocelot.jaxrs.doclet.sample.resources; @Path("/Recursive") public class RecursiveResource { @POST
public Recursive recurse(Recursive recursive) {
ryankennedy/swagger-jaxrs-doclet
jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/ObjectMapperRecorder.java
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ApiDeclaration.java // @JsonPropertyOrder({"apiVersion", "swaggerVersion", "basePath", "resourcePath", "apis", "models"}) // public class ApiDeclaration { // private String apiVersion; // private String swaggerVersion; // private String basePath; // private String resourcePath; // private Collection<Api> apis; // private Map<String, Model> models; // // @SuppressWarnings("unused") // private ApiDeclaration() { // } // // public ApiDeclaration(String apiVersion, String basePath, String resourcePath, Collection<Api> apis, Map<String, Model> models) { // this.apiVersion = apiVersion; // this.swaggerVersion = "1.1"; // this.basePath = basePath; // this.resourcePath = resourcePath; // this.apis = apis.isEmpty() ? null : apis; // this.models = models.isEmpty() ? null : models; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return swaggerVersion; // } // // public String getBasePath() { // return basePath; // } // // public String getResourcePath() { // return resourcePath; // } // // public Collection<Api> getApis() { // return apis; // } // // public Map<String, Model> getModels() { // return models; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApiDeclaration that = (ApiDeclaration) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(swaggerVersion, that.swaggerVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(resourcePath, that.resourcePath) // && Objects.equal(apis, that.apis) // && Objects.equal(models, that.models); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, swaggerVersion, basePath, resourcePath, apis, models); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("swaggerVersion", swaggerVersion) // .add("basePath", basePath) // .add("resourcePath", resourcePath) // .add("apis", apis) // .add("models", models) // .toString(); // } // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ResourceListing.java // public class ResourceListing { // private String apiVersion; // private String basePath; // private List<ResourceListingAPI> apis; // // @SuppressWarnings("unused") // private ResourceListing() { // } // // public ResourceListing(String apiVersion, String basePath, List<ResourceListingAPI> apis) { // this.apiVersion = apiVersion; // this.basePath = basePath; // this.apis = apis; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return "1.1"; // } // // public String getBasePath() { // return basePath; // } // // public List<ResourceListingAPI> getApis() { // return apis; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ResourceListing that = (ResourceListing) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(apis, that.apis); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, basePath, apis); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("basePath", basePath) // .add("apis", apis) // .toString(); // } // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.io.ByteStreams; import com.hypnoticocelot.jaxrs.doclet.model.ApiDeclaration; import com.hypnoticocelot.jaxrs.doclet.model.ResourceListing; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream;
package com.hypnoticocelot.jaxrs.doclet; public class ObjectMapperRecorder implements Recorder { private final ObjectMapper mapper = new ObjectMapper(); public ObjectMapperRecorder() { mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Override
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ApiDeclaration.java // @JsonPropertyOrder({"apiVersion", "swaggerVersion", "basePath", "resourcePath", "apis", "models"}) // public class ApiDeclaration { // private String apiVersion; // private String swaggerVersion; // private String basePath; // private String resourcePath; // private Collection<Api> apis; // private Map<String, Model> models; // // @SuppressWarnings("unused") // private ApiDeclaration() { // } // // public ApiDeclaration(String apiVersion, String basePath, String resourcePath, Collection<Api> apis, Map<String, Model> models) { // this.apiVersion = apiVersion; // this.swaggerVersion = "1.1"; // this.basePath = basePath; // this.resourcePath = resourcePath; // this.apis = apis.isEmpty() ? null : apis; // this.models = models.isEmpty() ? null : models; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return swaggerVersion; // } // // public String getBasePath() { // return basePath; // } // // public String getResourcePath() { // return resourcePath; // } // // public Collection<Api> getApis() { // return apis; // } // // public Map<String, Model> getModels() { // return models; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApiDeclaration that = (ApiDeclaration) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(swaggerVersion, that.swaggerVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(resourcePath, that.resourcePath) // && Objects.equal(apis, that.apis) // && Objects.equal(models, that.models); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, swaggerVersion, basePath, resourcePath, apis, models); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("swaggerVersion", swaggerVersion) // .add("basePath", basePath) // .add("resourcePath", resourcePath) // .add("apis", apis) // .add("models", models) // .toString(); // } // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ResourceListing.java // public class ResourceListing { // private String apiVersion; // private String basePath; // private List<ResourceListingAPI> apis; // // @SuppressWarnings("unused") // private ResourceListing() { // } // // public ResourceListing(String apiVersion, String basePath, List<ResourceListingAPI> apis) { // this.apiVersion = apiVersion; // this.basePath = basePath; // this.apis = apis; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return "1.1"; // } // // public String getBasePath() { // return basePath; // } // // public List<ResourceListingAPI> getApis() { // return apis; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ResourceListing that = (ResourceListing) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(apis, that.apis); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, basePath, apis); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("basePath", basePath) // .add("apis", apis) // .toString(); // } // } // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/ObjectMapperRecorder.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.io.ByteStreams; import com.hypnoticocelot.jaxrs.doclet.model.ApiDeclaration; import com.hypnoticocelot.jaxrs.doclet.model.ResourceListing; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; package com.hypnoticocelot.jaxrs.doclet; public class ObjectMapperRecorder implements Recorder { private final ObjectMapper mapper = new ObjectMapper(); public ObjectMapperRecorder() { mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Override
public void record(File file, ApiDeclaration declaration) throws IOException {
ryankennedy/swagger-jaxrs-doclet
jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/ObjectMapperRecorder.java
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ApiDeclaration.java // @JsonPropertyOrder({"apiVersion", "swaggerVersion", "basePath", "resourcePath", "apis", "models"}) // public class ApiDeclaration { // private String apiVersion; // private String swaggerVersion; // private String basePath; // private String resourcePath; // private Collection<Api> apis; // private Map<String, Model> models; // // @SuppressWarnings("unused") // private ApiDeclaration() { // } // // public ApiDeclaration(String apiVersion, String basePath, String resourcePath, Collection<Api> apis, Map<String, Model> models) { // this.apiVersion = apiVersion; // this.swaggerVersion = "1.1"; // this.basePath = basePath; // this.resourcePath = resourcePath; // this.apis = apis.isEmpty() ? null : apis; // this.models = models.isEmpty() ? null : models; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return swaggerVersion; // } // // public String getBasePath() { // return basePath; // } // // public String getResourcePath() { // return resourcePath; // } // // public Collection<Api> getApis() { // return apis; // } // // public Map<String, Model> getModels() { // return models; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApiDeclaration that = (ApiDeclaration) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(swaggerVersion, that.swaggerVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(resourcePath, that.resourcePath) // && Objects.equal(apis, that.apis) // && Objects.equal(models, that.models); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, swaggerVersion, basePath, resourcePath, apis, models); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("swaggerVersion", swaggerVersion) // .add("basePath", basePath) // .add("resourcePath", resourcePath) // .add("apis", apis) // .add("models", models) // .toString(); // } // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ResourceListing.java // public class ResourceListing { // private String apiVersion; // private String basePath; // private List<ResourceListingAPI> apis; // // @SuppressWarnings("unused") // private ResourceListing() { // } // // public ResourceListing(String apiVersion, String basePath, List<ResourceListingAPI> apis) { // this.apiVersion = apiVersion; // this.basePath = basePath; // this.apis = apis; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return "1.1"; // } // // public String getBasePath() { // return basePath; // } // // public List<ResourceListingAPI> getApis() { // return apis; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ResourceListing that = (ResourceListing) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(apis, that.apis); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, basePath, apis); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("basePath", basePath) // .add("apis", apis) // .toString(); // } // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.io.ByteStreams; import com.hypnoticocelot.jaxrs.doclet.model.ApiDeclaration; import com.hypnoticocelot.jaxrs.doclet.model.ResourceListing; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream;
package com.hypnoticocelot.jaxrs.doclet; public class ObjectMapperRecorder implements Recorder { private final ObjectMapper mapper = new ObjectMapper(); public ObjectMapperRecorder() { mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Override public void record(File file, ApiDeclaration declaration) throws IOException { mapper.writeValue(file, declaration); } @Override
// Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ApiDeclaration.java // @JsonPropertyOrder({"apiVersion", "swaggerVersion", "basePath", "resourcePath", "apis", "models"}) // public class ApiDeclaration { // private String apiVersion; // private String swaggerVersion; // private String basePath; // private String resourcePath; // private Collection<Api> apis; // private Map<String, Model> models; // // @SuppressWarnings("unused") // private ApiDeclaration() { // } // // public ApiDeclaration(String apiVersion, String basePath, String resourcePath, Collection<Api> apis, Map<String, Model> models) { // this.apiVersion = apiVersion; // this.swaggerVersion = "1.1"; // this.basePath = basePath; // this.resourcePath = resourcePath; // this.apis = apis.isEmpty() ? null : apis; // this.models = models.isEmpty() ? null : models; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return swaggerVersion; // } // // public String getBasePath() { // return basePath; // } // // public String getResourcePath() { // return resourcePath; // } // // public Collection<Api> getApis() { // return apis; // } // // public Map<String, Model> getModels() { // return models; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApiDeclaration that = (ApiDeclaration) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(swaggerVersion, that.swaggerVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(resourcePath, that.resourcePath) // && Objects.equal(apis, that.apis) // && Objects.equal(models, that.models); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, swaggerVersion, basePath, resourcePath, apis, models); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("swaggerVersion", swaggerVersion) // .add("basePath", basePath) // .add("resourcePath", resourcePath) // .add("apis", apis) // .add("models", models) // .toString(); // } // } // // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/model/ResourceListing.java // public class ResourceListing { // private String apiVersion; // private String basePath; // private List<ResourceListingAPI> apis; // // @SuppressWarnings("unused") // private ResourceListing() { // } // // public ResourceListing(String apiVersion, String basePath, List<ResourceListingAPI> apis) { // this.apiVersion = apiVersion; // this.basePath = basePath; // this.apis = apis; // } // // public String getApiVersion() { // return apiVersion; // } // // public String getSwaggerVersion() { // return "1.1"; // } // // public String getBasePath() { // return basePath; // } // // public List<ResourceListingAPI> getApis() { // return apis; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ResourceListing that = (ResourceListing) o; // return Objects.equal(apiVersion, that.apiVersion) // && Objects.equal(basePath, that.basePath) // && Objects.equal(apis, that.apis); // } // // @Override // public int hashCode() { // return Objects.hashCode(apiVersion, basePath, apis); // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("apiVersion", apiVersion) // .add("basePath", basePath) // .add("apis", apis) // .toString(); // } // } // Path: jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/ObjectMapperRecorder.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.io.ByteStreams; import com.hypnoticocelot.jaxrs.doclet.model.ApiDeclaration; import com.hypnoticocelot.jaxrs.doclet.model.ResourceListing; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; package com.hypnoticocelot.jaxrs.doclet; public class ObjectMapperRecorder implements Recorder { private final ObjectMapper mapper = new ObjectMapper(); public ObjectMapperRecorder() { mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Override public void record(File file, ApiDeclaration declaration) throws IOException { mapper.writeValue(file, declaration); } @Override
public void record(File file, ResourceListing listing) throws IOException {
ryankennedy/swagger-jaxrs-doclet
jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/resources/ModelResource.java
// Path: jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/api/ModelResourceModel.java // public class ModelResourceModel { // private final long modelId; // private final String title; // private final String description; // private final DateTime modified; // // public ModelResourceModel(long modelId, String title, String description, DateTime modified) { // //To change body of created methods use File | Settings | File Templates. // this.modelId = modelId; // this.title = title; // this.description = description; // this.modified = modified; // } // // public long getModelId() { // return modelId; // } // // public String getTitle() { // return title; // } // // public String getDescription() { // return description; // } // // public DateTime getModified() { // return modified; // } // }
import com.hypnoticocelot.jaxrs.doclet.sample.api.ModelResourceModel; import org.joda.time.DateTime; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType;
package com.hypnoticocelot.jaxrs.doclet.sample.resources; @Path("/ModelResource/{modelid}") @Produces(MediaType.APPLICATION_JSON) public class ModelResource { @GET
// Path: jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/api/ModelResourceModel.java // public class ModelResourceModel { // private final long modelId; // private final String title; // private final String description; // private final DateTime modified; // // public ModelResourceModel(long modelId, String title, String description, DateTime modified) { // //To change body of created methods use File | Settings | File Templates. // this.modelId = modelId; // this.title = title; // this.description = description; // this.modified = modified; // } // // public long getModelId() { // return modelId; // } // // public String getTitle() { // return title; // } // // public String getDescription() { // return description; // } // // public DateTime getModified() { // return modified; // } // } // Path: jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/resources/ModelResource.java import com.hypnoticocelot.jaxrs.doclet.sample.api.ModelResourceModel; import org.joda.time.DateTime; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; package com.hypnoticocelot.jaxrs.doclet.sample.resources; @Path("/ModelResource/{modelid}") @Produces(MediaType.APPLICATION_JSON) public class ModelResource { @GET
public ModelResourceModel getModel(@PathParam("modelid") long modelId) {
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/service/admin/SpsAdmin.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/CapabilitiesInterceptor.java // public interface CapabilitiesInterceptor { // // /** // * Enriches passed capabilities with appropriate information. This includes for example <b>Profile</b> // * description(s) of the intercepting SPS component. Another example is adding an <b>OperationMetadata</b> // * section describing operation information. // * // * @param capabilities // * the capabilities to intercept. // * @param httpBindings // * the supported operation bindings // */ // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings); // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceException.java // public abstract class InternalServiceException extends Exception { // // private static final long serialVersionUID = -1598594769157092219L; // // public static final int BAD_REQUEST = 400; // // private List<String> detailedMessages = new ArrayList<String>(); // private String exceptionCode; // private String locator; // // public InternalServiceException(String exceptionCode, String locator) { // this.exceptionCode = exceptionCode; // this.locator = locator; // } // // public String getExceptionCode() { // return exceptionCode; // } // // public void setExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getLocator() { // return locator; // } // // public void setLocator(String locator) { // this.locator = locator; // } // // public void addDetailedMessage(String detailedMessage) { // detailedMessages.add(detailedMessage); // } // // public Iterable<String> getDetailedMessages() { // return detailedMessages; // } // // public abstract int getHttpStatusCode(); // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/SpsOperationExtension.java // public interface SpsOperationExtension { // // public boolean isInterceptCapabilities(); // // public void setExtensionBinding(HttpBinding httpBinding); // }
import org.n52.ows.exception.OwsException; import org.n52.ows.exception.OwsExceptionReport; import org.n52.sps.service.CapabilitiesInterceptor; import org.n52.sps.service.InternalServiceException; import org.n52.sps.service.SpsOperationExtension; import org.x52North.schemas.sps.v2.InsertSensorOfferingDocument; import java.util.List; import org.apache.xmlbeans.XmlObject;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.admin; public interface SpsAdmin extends CapabilitiesInterceptor, SpsOperationExtension { final static String INSERT_SENSOR_OFFERING = "InsertSensorOffering"; final static String INSERT_RESOURCE = "insert"; final static String DELETE_SENSOR_OFFERING = "DeleteSensorOffering"; final static String DELETE_RESOURCE = "delete"; public void setInsertSensorOfferingListeners(List<InsertSensorOfferingListener> insertSensorOfferingListeners); public void setDeleteSensorOfferingListeners(List<DeleteSensorOfferingListener> deleteSensorOfferingListeners);
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/CapabilitiesInterceptor.java // public interface CapabilitiesInterceptor { // // /** // * Enriches passed capabilities with appropriate information. This includes for example <b>Profile</b> // * description(s) of the intercepting SPS component. Another example is adding an <b>OperationMetadata</b> // * section describing operation information. // * // * @param capabilities // * the capabilities to intercept. // * @param httpBindings // * the supported operation bindings // */ // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings); // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceException.java // public abstract class InternalServiceException extends Exception { // // private static final long serialVersionUID = -1598594769157092219L; // // public static final int BAD_REQUEST = 400; // // private List<String> detailedMessages = new ArrayList<String>(); // private String exceptionCode; // private String locator; // // public InternalServiceException(String exceptionCode, String locator) { // this.exceptionCode = exceptionCode; // this.locator = locator; // } // // public String getExceptionCode() { // return exceptionCode; // } // // public void setExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getLocator() { // return locator; // } // // public void setLocator(String locator) { // this.locator = locator; // } // // public void addDetailedMessage(String detailedMessage) { // detailedMessages.add(detailedMessage); // } // // public Iterable<String> getDetailedMessages() { // return detailedMessages; // } // // public abstract int getHttpStatusCode(); // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/SpsOperationExtension.java // public interface SpsOperationExtension { // // public boolean isInterceptCapabilities(); // // public void setExtensionBinding(HttpBinding httpBinding); // } // Path: 52n-sps-api/src/main/java/org/n52/sps/service/admin/SpsAdmin.java import org.n52.ows.exception.OwsException; import org.n52.ows.exception.OwsExceptionReport; import org.n52.sps.service.CapabilitiesInterceptor; import org.n52.sps.service.InternalServiceException; import org.n52.sps.service.SpsOperationExtension; import org.x52North.schemas.sps.v2.InsertSensorOfferingDocument; import java.util.List; import org.apache.xmlbeans.XmlObject; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.admin; public interface SpsAdmin extends CapabilitiesInterceptor, SpsOperationExtension { final static String INSERT_SENSOR_OFFERING = "InsertSensorOffering"; final static String INSERT_RESOURCE = "insert"; final static String DELETE_SENSOR_OFFERING = "DeleteSensorOffering"; final static String DELETE_RESOURCE = "delete"; public void setInsertSensorOfferingListeners(List<InsertSensorOfferingListener> insertSensorOfferingListeners); public void setDeleteSensorOfferingListeners(List<DeleteSensorOfferingListener> deleteSensorOfferingListeners);
public void insertSensorOffering(InsertSensorOfferingDocument offering, OwsExceptionReport exceptionReport) throws OwsException, InternalServiceException;
52North/SensorPlanningService
52n-sps-testplugin/src/test/java/org/n52/sps/sensor/cite/tasking/TextValuesDataRecordValidatorTest.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/SubmitTaskingRequest.java // public class SubmitTaskingRequest extends TaskingRequest { // // public SubmitTaskingRequest(SubmitDocument submitDoc) { // super(submitDoc); // } // // } // // Path: 52n-sps-api/src/test/java/org/n52/testing/utilities/FileContentLoader.java // public class FileContentLoader { // // /** // * Loads XML files which can be found via the <code>clazz</code>'s {@link ClassLoader}. If not found the // * {@link FileContentLoader}'s {@link ClassLoader} is asked to load the file. If file could not be found // * an exception is thrown. // * // * @param filePath // * the path to the file to be loaded. // * @param clazz // * the class which {@link ClassLoader} to be used. // * @return an XmlObject of the loaded file. // * @throws XmlException // * if file could not be parsed into XML // * @throws IOException // * if file could not be read. // * @throws IllegalArgumentException // * if file path is <code>null</code> or empty // * @throws FileNotFoundException // * if the resource could not be found be the <code>clazz</code>'s {@link ClassLoader} // */ // public static XmlObject loadXmlFileViaClassloader(String filePath, Class< ? > clazz) throws XmlException, // IOException { // if (filePath == null || filePath.isEmpty()) { // throw new IllegalArgumentException("Check file path: '" + filePath + "'."); // } // InputStream is = clazz.getResourceAsStream(filePath); // if (is == null) { // is = FileContentLoader.class.getResourceAsStream(filePath); // if (is == null) { // throw new FileNotFoundException("The resource at '" + filePath + "' cannot be found."); // } // } // return XmlObject.Factory.parse(is); // } // // }
import net.opengis.sps.x20.SubmitDocument; import net.opengis.swe.x20.DataRecordDocument; import net.opengis.swe.x20.DataRecordType; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.junit.Before; import org.junit.Test; import org.n52.ows.exception.InvalidParameterValueException; import org.n52.sps.tasking.SubmitTaskingRequest; import org.n52.testing.utilities.FileContentLoader; import static org.junit.Assert.fail; import java.io.IOException;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.cite.tasking; public class TextValuesDataRecordValidatorTest { private final static String TASKING_PARAMETERS_TEMPLATE = "/files/taskingParameters.xml"; private final static String VALID_SUBMIT_REQUEST = "/files/validSubmitRequest.xml"; private TextValuesDataRecordValidator validator;
// Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/SubmitTaskingRequest.java // public class SubmitTaskingRequest extends TaskingRequest { // // public SubmitTaskingRequest(SubmitDocument submitDoc) { // super(submitDoc); // } // // } // // Path: 52n-sps-api/src/test/java/org/n52/testing/utilities/FileContentLoader.java // public class FileContentLoader { // // /** // * Loads XML files which can be found via the <code>clazz</code>'s {@link ClassLoader}. If not found the // * {@link FileContentLoader}'s {@link ClassLoader} is asked to load the file. If file could not be found // * an exception is thrown. // * // * @param filePath // * the path to the file to be loaded. // * @param clazz // * the class which {@link ClassLoader} to be used. // * @return an XmlObject of the loaded file. // * @throws XmlException // * if file could not be parsed into XML // * @throws IOException // * if file could not be read. // * @throws IllegalArgumentException // * if file path is <code>null</code> or empty // * @throws FileNotFoundException // * if the resource could not be found be the <code>clazz</code>'s {@link ClassLoader} // */ // public static XmlObject loadXmlFileViaClassloader(String filePath, Class< ? > clazz) throws XmlException, // IOException { // if (filePath == null || filePath.isEmpty()) { // throw new IllegalArgumentException("Check file path: '" + filePath + "'."); // } // InputStream is = clazz.getResourceAsStream(filePath); // if (is == null) { // is = FileContentLoader.class.getResourceAsStream(filePath); // if (is == null) { // throw new FileNotFoundException("The resource at '" + filePath + "' cannot be found."); // } // } // return XmlObject.Factory.parse(is); // } // // } // Path: 52n-sps-testplugin/src/test/java/org/n52/sps/sensor/cite/tasking/TextValuesDataRecordValidatorTest.java import net.opengis.sps.x20.SubmitDocument; import net.opengis.swe.x20.DataRecordDocument; import net.opengis.swe.x20.DataRecordType; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.junit.Before; import org.junit.Test; import org.n52.ows.exception.InvalidParameterValueException; import org.n52.sps.tasking.SubmitTaskingRequest; import org.n52.testing.utilities.FileContentLoader; import static org.junit.Assert.fail; import java.io.IOException; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.cite.tasking; public class TextValuesDataRecordValidatorTest { private final static String TASKING_PARAMETERS_TEMPLATE = "/files/taskingParameters.xml"; private final static String VALID_SUBMIT_REQUEST = "/files/validSubmitRequest.xml"; private TextValuesDataRecordValidator validator;
private SubmitTaskingRequest validTaskingRequest;
52North/SensorPlanningService
52n-sps-testplugin/src/test/java/org/n52/sps/sensor/cite/tasking/TextValuesDataRecordValidatorTest.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/SubmitTaskingRequest.java // public class SubmitTaskingRequest extends TaskingRequest { // // public SubmitTaskingRequest(SubmitDocument submitDoc) { // super(submitDoc); // } // // } // // Path: 52n-sps-api/src/test/java/org/n52/testing/utilities/FileContentLoader.java // public class FileContentLoader { // // /** // * Loads XML files which can be found via the <code>clazz</code>'s {@link ClassLoader}. If not found the // * {@link FileContentLoader}'s {@link ClassLoader} is asked to load the file. If file could not be found // * an exception is thrown. // * // * @param filePath // * the path to the file to be loaded. // * @param clazz // * the class which {@link ClassLoader} to be used. // * @return an XmlObject of the loaded file. // * @throws XmlException // * if file could not be parsed into XML // * @throws IOException // * if file could not be read. // * @throws IllegalArgumentException // * if file path is <code>null</code> or empty // * @throws FileNotFoundException // * if the resource could not be found be the <code>clazz</code>'s {@link ClassLoader} // */ // public static XmlObject loadXmlFileViaClassloader(String filePath, Class< ? > clazz) throws XmlException, // IOException { // if (filePath == null || filePath.isEmpty()) { // throw new IllegalArgumentException("Check file path: '" + filePath + "'."); // } // InputStream is = clazz.getResourceAsStream(filePath); // if (is == null) { // is = FileContentLoader.class.getResourceAsStream(filePath); // if (is == null) { // throw new FileNotFoundException("The resource at '" + filePath + "' cannot be found."); // } // } // return XmlObject.Factory.parse(is); // } // // }
import net.opengis.sps.x20.SubmitDocument; import net.opengis.swe.x20.DataRecordDocument; import net.opengis.swe.x20.DataRecordType; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.junit.Before; import org.junit.Test; import org.n52.ows.exception.InvalidParameterValueException; import org.n52.sps.tasking.SubmitTaskingRequest; import org.n52.testing.utilities.FileContentLoader; import static org.junit.Assert.fail; import java.io.IOException;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.cite.tasking; public class TextValuesDataRecordValidatorTest { private final static String TASKING_PARAMETERS_TEMPLATE = "/files/taskingParameters.xml"; private final static String VALID_SUBMIT_REQUEST = "/files/validSubmitRequest.xml"; private TextValuesDataRecordValidator validator; private SubmitTaskingRequest validTaskingRequest; private DataRecordType dataRecordTemplate; @Before public void setUp() throws Exception { dataRecordTemplate = getTaskingParamters(); validTaskingRequest = getValidTaskingRequest(); } private DataRecordType getTaskingParamters() throws XmlException, IOException {
// Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/SubmitTaskingRequest.java // public class SubmitTaskingRequest extends TaskingRequest { // // public SubmitTaskingRequest(SubmitDocument submitDoc) { // super(submitDoc); // } // // } // // Path: 52n-sps-api/src/test/java/org/n52/testing/utilities/FileContentLoader.java // public class FileContentLoader { // // /** // * Loads XML files which can be found via the <code>clazz</code>'s {@link ClassLoader}. If not found the // * {@link FileContentLoader}'s {@link ClassLoader} is asked to load the file. If file could not be found // * an exception is thrown. // * // * @param filePath // * the path to the file to be loaded. // * @param clazz // * the class which {@link ClassLoader} to be used. // * @return an XmlObject of the loaded file. // * @throws XmlException // * if file could not be parsed into XML // * @throws IOException // * if file could not be read. // * @throws IllegalArgumentException // * if file path is <code>null</code> or empty // * @throws FileNotFoundException // * if the resource could not be found be the <code>clazz</code>'s {@link ClassLoader} // */ // public static XmlObject loadXmlFileViaClassloader(String filePath, Class< ? > clazz) throws XmlException, // IOException { // if (filePath == null || filePath.isEmpty()) { // throw new IllegalArgumentException("Check file path: '" + filePath + "'."); // } // InputStream is = clazz.getResourceAsStream(filePath); // if (is == null) { // is = FileContentLoader.class.getResourceAsStream(filePath); // if (is == null) { // throw new FileNotFoundException("The resource at '" + filePath + "' cannot be found."); // } // } // return XmlObject.Factory.parse(is); // } // // } // Path: 52n-sps-testplugin/src/test/java/org/n52/sps/sensor/cite/tasking/TextValuesDataRecordValidatorTest.java import net.opengis.sps.x20.SubmitDocument; import net.opengis.swe.x20.DataRecordDocument; import net.opengis.swe.x20.DataRecordType; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.junit.Before; import org.junit.Test; import org.n52.ows.exception.InvalidParameterValueException; import org.n52.sps.tasking.SubmitTaskingRequest; import org.n52.testing.utilities.FileContentLoader; import static org.junit.Assert.fail; import java.io.IOException; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.cite.tasking; public class TextValuesDataRecordValidatorTest { private final static String TASKING_PARAMETERS_TEMPLATE = "/files/taskingParameters.xml"; private final static String VALID_SUBMIT_REQUEST = "/files/validSubmitRequest.xml"; private TextValuesDataRecordValidator validator; private SubmitTaskingRequest validTaskingRequest; private DataRecordType dataRecordTemplate; @Before public void setUp() throws Exception { dataRecordTemplate = getTaskingParamters(); validTaskingRequest = getValidTaskingRequest(); } private DataRecordType getTaskingParamters() throws XmlException, IOException {
XmlObject template = FileContentLoader.loadXmlFileViaClassloader(TASKING_PARAMETERS_TEMPLATE, getClass());
52North/SensorPlanningService
52n-sps-api/src/test/java/org/n52/sps/tasking/TaskingRequestStatusTest.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/TaskingRequestStatus.java // public enum TaskingRequestStatus { // // ACCEPTED(TaskingRequestStatusCodeEnumerationType.ACCEPTED), // PENDING(TaskingRequestStatusCodeEnumerationType.PENDING), // REJECTED(TaskingRequestStatusCodeEnumerationType.REJECTED); // // private TaskingRequestStatusCodeEnumerationType.Enum status; // // TaskingRequestStatus(TaskingRequestStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskingRequestStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static TaskingRequestStatus getTaskingRequestStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // }
import org.junit.Test; import org.n52.sps.tasking.TaskingRequestStatus; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.tasking; public class TaskingRequestStatusTest { @Test public void testGetSensorTaskStatus() {
// Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/TaskingRequestStatus.java // public enum TaskingRequestStatus { // // ACCEPTED(TaskingRequestStatusCodeEnumerationType.ACCEPTED), // PENDING(TaskingRequestStatusCodeEnumerationType.PENDING), // REJECTED(TaskingRequestStatusCodeEnumerationType.REJECTED); // // private TaskingRequestStatusCodeEnumerationType.Enum status; // // TaskingRequestStatus(TaskingRequestStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskingRequestStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static TaskingRequestStatus getTaskingRequestStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // } // Path: 52n-sps-api/src/test/java/org/n52/sps/tasking/TaskingRequestStatusTest.java import org.junit.Test; import org.n52.sps.tasking.TaskingRequestStatus; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.tasking; public class TaskingRequestStatusTest { @Test public void testGetSensorTaskStatus() {
assertEquals(TaskingRequestStatus.ACCEPTED, TaskingRequestStatus.getTaskingRequestStatus("Accepted"));
52North/SensorPlanningService
52n-sps-webapp/src/main/java/org/n52/sps/service/AutoWiredSPSComponentProvider.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/BasicSensorPlanner.java // public interface BasicSensorPlanner extends CapabilitiesInterceptor { // // final static String CORE_CONFORMANCE_CLASS = "http://www.opengis.net/spec/SPS/2.0/conf/Core"; // // final static String DESCRIBE_RESULT_ACCESS = "DescribeResultAccess"; // // final static String DESCRIBE_TASKING = "DescribeTasking"; // // final static String GET_CAPABILITIES = "GetCapabilities"; // // final static String GET_STATUS = "GetStatus"; // // final static String GET_TASK = "GetTask"; // // final static String SUBMIT = "Submit"; // // /** // * allows a client to retrieve information, which enables access to the data produced by the asset. The // * server response may contain references to any kind of data accessing OGC Web services such as SOS, WMS, // * WCS or WFS. // * // * @param describeResultAccess // * the request // * @return the result access information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject describeResultAccess(DescribeResultAccessDocument describeResultAccess) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to request the information that is needed in order to prepare a tasking request // * targeted at the assets that are supported by the SPS and that are selected by the client. The server // * will return information about all parameters that have to be set by the client in order to create a // * task. // * // * @param describeTasking // * the request // * @return the tasking information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject describeTasking(DescribeTaskingDocument describeTasking) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to request and receive service metadata documents that describe the capabilities of the // * specific server implementation. This operation also supports negotiation of the specification version // * being used for client-server interactions. // * // * @param getCapabilities // * the request // * @return the capabilities information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getCapabilities(GetCapabilitiesDocument getCapabilities) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to receive information about the current status of the requested task. // * // * @param getStatus // * the request // * @return the status information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getStatus(GetStatusDocument getStatus) throws OwsException, OwsExceptionReport; // // /** // * Returns complete information about the requested task. // * // * @param getTask // * the request // * @return the task information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getTask(GetTaskDocument getTask) throws OwsException, OwsExceptionReport; // // /** // * Submits a task. Depending on the facaded asset, it may perform a simple modification of the asset or // * start a complex mission. // * // * @param submit // * the request // * @return the submit information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject submit(SubmitDocument submit) throws OwsException, OwsExceptionReport; // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/SensorProvider.java // public interface SensorProvider extends CapabilitiesInterceptor { // // final static String SENSOR_PROVIDER_CONFORMANCE_CLASS = "http://www.opengis.net/spec/SPS/2.0/conf/SensorProvider"; // // final static String DESCRIBE_SENSOR = "DescribeSensor"; // // /** // * This operation allows a client to request a detailed description of a sensor. The request can be // * targeted at a description that was valid at a certain point in or during a certain period of time in // * the past [OGC 09-001 clause 11]. // * // * @param describeSensor // * the request // * @return the sensor information // * @throws OwsException // * @throws OwsExceptionReport // */ // public DescribeSensorResponseDocument describeSensor(DescribeSensorDocument describeSensor) throws OwsException, OwsExceptionReport; // }
import org.n52.sps.service.core.BasicSensorPlanner; import org.n52.sps.service.core.SensorProvider; import org.springframework.beans.factory.annotation.Autowired;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service; public class AutoWiredSPSComponentProvider extends SpsComponentProvider { @Autowired
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/BasicSensorPlanner.java // public interface BasicSensorPlanner extends CapabilitiesInterceptor { // // final static String CORE_CONFORMANCE_CLASS = "http://www.opengis.net/spec/SPS/2.0/conf/Core"; // // final static String DESCRIBE_RESULT_ACCESS = "DescribeResultAccess"; // // final static String DESCRIBE_TASKING = "DescribeTasking"; // // final static String GET_CAPABILITIES = "GetCapabilities"; // // final static String GET_STATUS = "GetStatus"; // // final static String GET_TASK = "GetTask"; // // final static String SUBMIT = "Submit"; // // /** // * allows a client to retrieve information, which enables access to the data produced by the asset. The // * server response may contain references to any kind of data accessing OGC Web services such as SOS, WMS, // * WCS or WFS. // * // * @param describeResultAccess // * the request // * @return the result access information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject describeResultAccess(DescribeResultAccessDocument describeResultAccess) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to request the information that is needed in order to prepare a tasking request // * targeted at the assets that are supported by the SPS and that are selected by the client. The server // * will return information about all parameters that have to be set by the client in order to create a // * task. // * // * @param describeTasking // * the request // * @return the tasking information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject describeTasking(DescribeTaskingDocument describeTasking) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to request and receive service metadata documents that describe the capabilities of the // * specific server implementation. This operation also supports negotiation of the specification version // * being used for client-server interactions. // * // * @param getCapabilities // * the request // * @return the capabilities information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getCapabilities(GetCapabilitiesDocument getCapabilities) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to receive information about the current status of the requested task. // * // * @param getStatus // * the request // * @return the status information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getStatus(GetStatusDocument getStatus) throws OwsException, OwsExceptionReport; // // /** // * Returns complete information about the requested task. // * // * @param getTask // * the request // * @return the task information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getTask(GetTaskDocument getTask) throws OwsException, OwsExceptionReport; // // /** // * Submits a task. Depending on the facaded asset, it may perform a simple modification of the asset or // * start a complex mission. // * // * @param submit // * the request // * @return the submit information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject submit(SubmitDocument submit) throws OwsException, OwsExceptionReport; // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/SensorProvider.java // public interface SensorProvider extends CapabilitiesInterceptor { // // final static String SENSOR_PROVIDER_CONFORMANCE_CLASS = "http://www.opengis.net/spec/SPS/2.0/conf/SensorProvider"; // // final static String DESCRIBE_SENSOR = "DescribeSensor"; // // /** // * This operation allows a client to request a detailed description of a sensor. The request can be // * targeted at a description that was valid at a certain point in or during a certain period of time in // * the past [OGC 09-001 clause 11]. // * // * @param describeSensor // * the request // * @return the sensor information // * @throws OwsException // * @throws OwsExceptionReport // */ // public DescribeSensorResponseDocument describeSensor(DescribeSensorDocument describeSensor) throws OwsException, OwsExceptionReport; // } // Path: 52n-sps-webapp/src/main/java/org/n52/sps/service/AutoWiredSPSComponentProvider.java import org.n52.sps.service.core.BasicSensorPlanner; import org.n52.sps.service.core.SensorProvider; import org.springframework.beans.factory.annotation.Autowired; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service; public class AutoWiredSPSComponentProvider extends SpsComponentProvider { @Autowired
public AutoWiredSPSComponentProvider(BasicSensorPlanner basicSensorPlanner, SensorProvider sensorProvider) {
52North/SensorPlanningService
52n-sps-webapp/src/main/java/org/n52/sps/service/AutoWiredSPSComponentProvider.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/BasicSensorPlanner.java // public interface BasicSensorPlanner extends CapabilitiesInterceptor { // // final static String CORE_CONFORMANCE_CLASS = "http://www.opengis.net/spec/SPS/2.0/conf/Core"; // // final static String DESCRIBE_RESULT_ACCESS = "DescribeResultAccess"; // // final static String DESCRIBE_TASKING = "DescribeTasking"; // // final static String GET_CAPABILITIES = "GetCapabilities"; // // final static String GET_STATUS = "GetStatus"; // // final static String GET_TASK = "GetTask"; // // final static String SUBMIT = "Submit"; // // /** // * allows a client to retrieve information, which enables access to the data produced by the asset. The // * server response may contain references to any kind of data accessing OGC Web services such as SOS, WMS, // * WCS or WFS. // * // * @param describeResultAccess // * the request // * @return the result access information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject describeResultAccess(DescribeResultAccessDocument describeResultAccess) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to request the information that is needed in order to prepare a tasking request // * targeted at the assets that are supported by the SPS and that are selected by the client. The server // * will return information about all parameters that have to be set by the client in order to create a // * task. // * // * @param describeTasking // * the request // * @return the tasking information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject describeTasking(DescribeTaskingDocument describeTasking) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to request and receive service metadata documents that describe the capabilities of the // * specific server implementation. This operation also supports negotiation of the specification version // * being used for client-server interactions. // * // * @param getCapabilities // * the request // * @return the capabilities information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getCapabilities(GetCapabilitiesDocument getCapabilities) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to receive information about the current status of the requested task. // * // * @param getStatus // * the request // * @return the status information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getStatus(GetStatusDocument getStatus) throws OwsException, OwsExceptionReport; // // /** // * Returns complete information about the requested task. // * // * @param getTask // * the request // * @return the task information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getTask(GetTaskDocument getTask) throws OwsException, OwsExceptionReport; // // /** // * Submits a task. Depending on the facaded asset, it may perform a simple modification of the asset or // * start a complex mission. // * // * @param submit // * the request // * @return the submit information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject submit(SubmitDocument submit) throws OwsException, OwsExceptionReport; // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/SensorProvider.java // public interface SensorProvider extends CapabilitiesInterceptor { // // final static String SENSOR_PROVIDER_CONFORMANCE_CLASS = "http://www.opengis.net/spec/SPS/2.0/conf/SensorProvider"; // // final static String DESCRIBE_SENSOR = "DescribeSensor"; // // /** // * This operation allows a client to request a detailed description of a sensor. The request can be // * targeted at a description that was valid at a certain point in or during a certain period of time in // * the past [OGC 09-001 clause 11]. // * // * @param describeSensor // * the request // * @return the sensor information // * @throws OwsException // * @throws OwsExceptionReport // */ // public DescribeSensorResponseDocument describeSensor(DescribeSensorDocument describeSensor) throws OwsException, OwsExceptionReport; // }
import org.n52.sps.service.core.BasicSensorPlanner; import org.n52.sps.service.core.SensorProvider; import org.springframework.beans.factory.annotation.Autowired;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service; public class AutoWiredSPSComponentProvider extends SpsComponentProvider { @Autowired
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/BasicSensorPlanner.java // public interface BasicSensorPlanner extends CapabilitiesInterceptor { // // final static String CORE_CONFORMANCE_CLASS = "http://www.opengis.net/spec/SPS/2.0/conf/Core"; // // final static String DESCRIBE_RESULT_ACCESS = "DescribeResultAccess"; // // final static String DESCRIBE_TASKING = "DescribeTasking"; // // final static String GET_CAPABILITIES = "GetCapabilities"; // // final static String GET_STATUS = "GetStatus"; // // final static String GET_TASK = "GetTask"; // // final static String SUBMIT = "Submit"; // // /** // * allows a client to retrieve information, which enables access to the data produced by the asset. The // * server response may contain references to any kind of data accessing OGC Web services such as SOS, WMS, // * WCS or WFS. // * // * @param describeResultAccess // * the request // * @return the result access information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject describeResultAccess(DescribeResultAccessDocument describeResultAccess) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to request the information that is needed in order to prepare a tasking request // * targeted at the assets that are supported by the SPS and that are selected by the client. The server // * will return information about all parameters that have to be set by the client in order to create a // * task. // * // * @param describeTasking // * the request // * @return the tasking information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject describeTasking(DescribeTaskingDocument describeTasking) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to request and receive service metadata documents that describe the capabilities of the // * specific server implementation. This operation also supports negotiation of the specification version // * being used for client-server interactions. // * // * @param getCapabilities // * the request // * @return the capabilities information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getCapabilities(GetCapabilitiesDocument getCapabilities) throws OwsException, OwsExceptionReport; // // /** // * Allows a client to receive information about the current status of the requested task. // * // * @param getStatus // * the request // * @return the status information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getStatus(GetStatusDocument getStatus) throws OwsException, OwsExceptionReport; // // /** // * Returns complete information about the requested task. // * // * @param getTask // * the request // * @return the task information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject getTask(GetTaskDocument getTask) throws OwsException, OwsExceptionReport; // // /** // * Submits a task. Depending on the facaded asset, it may perform a simple modification of the asset or // * start a complex mission. // * // * @param submit // * the request // * @return the submit information // * @throws OwsException // * @throws OwsExceptionReport // */ // public XmlObject submit(SubmitDocument submit) throws OwsException, OwsExceptionReport; // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/SensorProvider.java // public interface SensorProvider extends CapabilitiesInterceptor { // // final static String SENSOR_PROVIDER_CONFORMANCE_CLASS = "http://www.opengis.net/spec/SPS/2.0/conf/SensorProvider"; // // final static String DESCRIBE_SENSOR = "DescribeSensor"; // // /** // * This operation allows a client to request a detailed description of a sensor. The request can be // * targeted at a description that was valid at a certain point in or during a certain period of time in // * the past [OGC 09-001 clause 11]. // * // * @param describeSensor // * the request // * @return the sensor information // * @throws OwsException // * @throws OwsExceptionReport // */ // public DescribeSensorResponseDocument describeSensor(DescribeSensorDocument describeSensor) throws OwsException, OwsExceptionReport; // } // Path: 52n-sps-webapp/src/main/java/org/n52/sps/service/AutoWiredSPSComponentProvider.java import org.n52.sps.service.core.BasicSensorPlanner; import org.n52.sps.service.core.SensorProvider; import org.springframework.beans.factory.annotation.Autowired; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service; public class AutoWiredSPSComponentProvider extends SpsComponentProvider { @Autowired
public AutoWiredSPSComponentProvider(BasicSensorPlanner basicSensorPlanner, SensorProvider sensorProvider) {
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/service/admin/InvalidSensorInformationException.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceException.java // public abstract class InternalServiceException extends Exception { // // private static final long serialVersionUID = -1598594769157092219L; // // public static final int BAD_REQUEST = 400; // // private List<String> detailedMessages = new ArrayList<String>(); // private String exceptionCode; // private String locator; // // public InternalServiceException(String exceptionCode, String locator) { // this.exceptionCode = exceptionCode; // this.locator = locator; // } // // public String getExceptionCode() { // return exceptionCode; // } // // public void setExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getLocator() { // return locator; // } // // public void setLocator(String locator) { // this.locator = locator; // } // // public void addDetailedMessage(String detailedMessage) { // detailedMessages.add(detailedMessage); // } // // public Iterable<String> getDetailedMessages() { // return detailedMessages; // } // // public abstract int getHttpStatusCode(); // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceExceptionCode.java // public enum InternalServiceExceptionCode { // // WRONG_PLUGIN_TYPE_RELATION("WrongPluginTypeRelation"), // MISSING_SENSOR_INFORMATION("MissingSensorInformation"), // UNKNOWN_SERVICE_INSTANCE("UnknownServiceInstance"); // // private String exceptionCode; // // private InternalServiceExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getExceptionCode() { // return exceptionCode; // } // }
import org.n52.sps.service.InternalServiceException; import org.n52.sps.service.InternalServiceExceptionCode;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.admin; public class InvalidSensorInformationException extends InternalServiceException { private static final long serialVersionUID = -7661454857813095434L; public InvalidSensorInformationException(String locator) {
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceException.java // public abstract class InternalServiceException extends Exception { // // private static final long serialVersionUID = -1598594769157092219L; // // public static final int BAD_REQUEST = 400; // // private List<String> detailedMessages = new ArrayList<String>(); // private String exceptionCode; // private String locator; // // public InternalServiceException(String exceptionCode, String locator) { // this.exceptionCode = exceptionCode; // this.locator = locator; // } // // public String getExceptionCode() { // return exceptionCode; // } // // public void setExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getLocator() { // return locator; // } // // public void setLocator(String locator) { // this.locator = locator; // } // // public void addDetailedMessage(String detailedMessage) { // detailedMessages.add(detailedMessage); // } // // public Iterable<String> getDetailedMessages() { // return detailedMessages; // } // // public abstract int getHttpStatusCode(); // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceExceptionCode.java // public enum InternalServiceExceptionCode { // // WRONG_PLUGIN_TYPE_RELATION("WrongPluginTypeRelation"), // MISSING_SENSOR_INFORMATION("MissingSensorInformation"), // UNKNOWN_SERVICE_INSTANCE("UnknownServiceInstance"); // // private String exceptionCode; // // private InternalServiceExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getExceptionCode() { // return exceptionCode; // } // } // Path: 52n-sps-api/src/main/java/org/n52/sps/service/admin/InvalidSensorInformationException.java import org.n52.sps.service.InternalServiceException; import org.n52.sps.service.InternalServiceExceptionCode; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.admin; public class InvalidSensorInformationException extends InternalServiceException { private static final long serialVersionUID = -7661454857813095434L; public InvalidSensorInformationException(String locator) {
super(InternalServiceExceptionCode.MISSING_SENSOR_INFORMATION.toString(), locator);
52North/SensorPlanningService
52n-sps-webapp/src/main/java/org/n52/sps/control/rest/TasksRestComponent.java
// Path: 52n-sps-rest/src/main/java/org/n52/sps/service/rest/TaskService.java // public interface TaskService { // // public List<String> getTaskIds(String procedure_id); // // }
import org.n52.sps.service.rest.TaskService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import static org.springframework.web.bind.annotation.RequestMethod.GET; import java.util.List;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.control.rest; @Controller @RequestMapping("/tasks") public class TasksRestComponent {
// Path: 52n-sps-rest/src/main/java/org/n52/sps/service/rest/TaskService.java // public interface TaskService { // // public List<String> getTaskIds(String procedure_id); // // } // Path: 52n-sps-webapp/src/main/java/org/n52/sps/control/rest/TasksRestComponent.java import org.n52.sps.service.rest.TaskService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import static org.springframework.web.bind.annotation.RequestMethod.GET; import java.util.List; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.control.rest; @Controller @RequestMapping("/tasks") public class TasksRestComponent {
private TaskService taskService;
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/util/encoding/binary/BinaryEncoderDecoder.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/EncodingException.java // public class EncodingException extends Exception { // // private static final long serialVersionUID = 6668408941898169625L; // // public EncodingException(String message, Throwable throwable) { // super(message, throwable); // } // // public EncodingException(String message) { // super(message); // } // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/SweEncoderDecoder.java // public interface SweEncoderDecoder<T, E> { // // public static class Factory { // // public static TextEncoderDecoder createTextEncoderDecoder(AbstractEncodingType encoding) { // // XmlHelper.qualifyWith(TextEncodingDocument.type, encoding); TODO check this qualifying principle and add tests for it // TextEncodingDocument textEncoding = XmlHelper.substituteWithTextEncoding(encoding); // return new TextEncoderDecoder(textEncoding.getTextEncoding()); // } // // public static XmlEncoderDecoder createXmlEncoderDecoder(AbstractEncodingType encoding) { // XMLEncodingDocument xmlEncoding = XmlHelper.substituteWithXmlEncoding(encoding); // return new XmlEncoderDecoder(xmlEncoding.getXMLEncoding()); // } // // public static BinaryEncoderDecoder createBinaryEncoderDecoder(AbstractEncodingType encoding) { // BinaryEncodingDocument binaryEncoding = XmlHelper.substituteWithBinaryEncoding(encoding); // return new BinaryEncoderDecoder(binaryEncoding.getBinaryEncoding()); // } // // } // // /** // * @param toEncode // * the data representation to be encoded. // * @return the encoded data. // * @throws EncodingException // * if encoding fails. // */ // public E encode(T toEncode) throws EncodingException; // // /** // * @param toDecode // * a generic type representation to be decoded. // * @return the decoded data. // * @throws EncodingException // * if decoding fails. // */ // public T decode(E toDecode) throws EncodingException; // // /** // * @param toDecode // * an xml data representation to be decoded. // * @return the decoded data. // * @throws EncodingException // * if decoding fails. // */ // public T decode(XmlObject toDecode) throws EncodingException; // // }
import org.n52.sps.util.encoding.EncodingException; import org.n52.sps.util.encoding.SweEncoderDecoder; import net.opengis.swe.x20.BinaryEncodingType; import org.apache.xmlbeans.XmlObject;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.util.encoding.binary; // TODO implement BinaryencoderDecoder public class BinaryEncoderDecoder implements SweEncoderDecoder<Void, Void> { public static final String BINARY_ENCODING = "http://www.opengis.net/swe/2.0/BinaryEncoding"; public BinaryEncoderDecoder(BinaryEncodingType binaryEncoding) { // TODO Auto-generated constructor stub }
// Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/EncodingException.java // public class EncodingException extends Exception { // // private static final long serialVersionUID = 6668408941898169625L; // // public EncodingException(String message, Throwable throwable) { // super(message, throwable); // } // // public EncodingException(String message) { // super(message); // } // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/SweEncoderDecoder.java // public interface SweEncoderDecoder<T, E> { // // public static class Factory { // // public static TextEncoderDecoder createTextEncoderDecoder(AbstractEncodingType encoding) { // // XmlHelper.qualifyWith(TextEncodingDocument.type, encoding); TODO check this qualifying principle and add tests for it // TextEncodingDocument textEncoding = XmlHelper.substituteWithTextEncoding(encoding); // return new TextEncoderDecoder(textEncoding.getTextEncoding()); // } // // public static XmlEncoderDecoder createXmlEncoderDecoder(AbstractEncodingType encoding) { // XMLEncodingDocument xmlEncoding = XmlHelper.substituteWithXmlEncoding(encoding); // return new XmlEncoderDecoder(xmlEncoding.getXMLEncoding()); // } // // public static BinaryEncoderDecoder createBinaryEncoderDecoder(AbstractEncodingType encoding) { // BinaryEncodingDocument binaryEncoding = XmlHelper.substituteWithBinaryEncoding(encoding); // return new BinaryEncoderDecoder(binaryEncoding.getBinaryEncoding()); // } // // } // // /** // * @param toEncode // * the data representation to be encoded. // * @return the encoded data. // * @throws EncodingException // * if encoding fails. // */ // public E encode(T toEncode) throws EncodingException; // // /** // * @param toDecode // * a generic type representation to be decoded. // * @return the decoded data. // * @throws EncodingException // * if decoding fails. // */ // public T decode(E toDecode) throws EncodingException; // // /** // * @param toDecode // * an xml data representation to be decoded. // * @return the decoded data. // * @throws EncodingException // * if decoding fails. // */ // public T decode(XmlObject toDecode) throws EncodingException; // // } // Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/binary/BinaryEncoderDecoder.java import org.n52.sps.util.encoding.EncodingException; import org.n52.sps.util.encoding.SweEncoderDecoder; import net.opengis.swe.x20.BinaryEncodingType; import org.apache.xmlbeans.XmlObject; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.util.encoding.binary; // TODO implement BinaryencoderDecoder public class BinaryEncoderDecoder implements SweEncoderDecoder<Void, Void> { public static final String BINARY_ENCODING = "http://www.opengis.net/swe/2.0/BinaryEncoding"; public BinaryEncoderDecoder(BinaryEncodingType binaryEncoding) { // TODO Auto-generated constructor stub }
public Void encode(Void toEncode) throws EncodingException {
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/sensor/result/ServiceNotAvailable.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/DataUnavailableCode.java // public enum DataUnavailableCode { // // DATA_NOT_AVAILABLE("DataNotAvailable"), // DATA_SERVICE_UNAVAILABLE("DataServiceUnavailable"); // // private String code; // // private DataUnavailableCode(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // }
import org.n52.sps.service.core.DataUnavailableCode; import net.opengis.sps.x20.DataNotAvailableType; import net.opengis.sps.x20.DescribeResultAccessResponseType.Availability; import net.opengis.sps.x20.DescribeResultAccessResponseType.Availability.Unavailable;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.result; public final class ServiceNotAvailable implements ResultAccessAvailabilityDescriptor { private final Availability availability = Availability.Factory.newInstance(); public ServiceNotAvailable(String... messages) { Unavailable unavailable = availability.addNewUnavailable(); DataNotAvailableType dataNotAvailable = unavailable.addNewDataNotAvailable();
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/DataUnavailableCode.java // public enum DataUnavailableCode { // // DATA_NOT_AVAILABLE("DataNotAvailable"), // DATA_SERVICE_UNAVAILABLE("DataServiceUnavailable"); // // private String code; // // private DataUnavailableCode(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // } // Path: 52n-sps-api/src/main/java/org/n52/sps/sensor/result/ServiceNotAvailable.java import org.n52.sps.service.core.DataUnavailableCode; import net.opengis.sps.x20.DataNotAvailableType; import net.opengis.sps.x20.DescribeResultAccessResponseType.Availability; import net.opengis.sps.x20.DescribeResultAccessResponseType.Availability.Unavailable; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.result; public final class ServiceNotAvailable implements ResultAccessAvailabilityDescriptor { private final Availability availability = Availability.Factory.newInstance(); public ServiceNotAvailable(String... messages) { Unavailable unavailable = availability.addNewUnavailable(); DataNotAvailableType dataNotAvailable = unavailable.addNewDataNotAvailable();
dataNotAvailable.setUnavailableCode(DataUnavailableCode.DATA_SERVICE_UNAVAILABLE.getCode());
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/service/update/ModificationOfFinalizedTaskException.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/SpsExceptionCode.java // public enum SpsExceptionCode { // // STATUS_INFORMATION_EXPIRED("StatusInformationExpired"), // MODIFICATION_OF_FINALIZED_TASK("ModificationOfFinalizedTask"); // // private String exceptionCode; // // private SpsExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getExceptionCode() { // return exceptionCode; // } // }
import org.n52.ows.exception.OwsException; import org.n52.sps.service.SpsExceptionCode;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.update; /** * The client attempted to modify (e.g. cancel, update or confirm) a task that was already finalized. */ public class ModificationOfFinalizedTaskException extends OwsException { private static final long serialVersionUID = 8145983711533554164L; public ModificationOfFinalizedTaskException() {
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/SpsExceptionCode.java // public enum SpsExceptionCode { // // STATUS_INFORMATION_EXPIRED("StatusInformationExpired"), // MODIFICATION_OF_FINALIZED_TASK("ModificationOfFinalizedTask"); // // private String exceptionCode; // // private SpsExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getExceptionCode() { // return exceptionCode; // } // } // Path: 52n-sps-api/src/main/java/org/n52/sps/service/update/ModificationOfFinalizedTaskException.java import org.n52.ows.exception.OwsException; import org.n52.sps.service.SpsExceptionCode; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.update; /** * The client attempted to modify (e.g. cancel, update or confirm) a task that was already finalized. */ public class ModificationOfFinalizedTaskException extends OwsException { private static final long serialVersionUID = 8145983711533554164L; public ModificationOfFinalizedTaskException() {
super(SpsExceptionCode.MODIFICATION_OF_FINALIZED_TASK.getExceptionCode());
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/util/encoding/xml/XmlEncoderDecoder.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/EncodingException.java // public class EncodingException extends Exception { // // private static final long serialVersionUID = 6668408941898169625L; // // public EncodingException(String message, Throwable throwable) { // super(message, throwable); // } // // public EncodingException(String message) { // super(message); // } // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/SweEncoderDecoder.java // public interface SweEncoderDecoder<T, E> { // // public static class Factory { // // public static TextEncoderDecoder createTextEncoderDecoder(AbstractEncodingType encoding) { // // XmlHelper.qualifyWith(TextEncodingDocument.type, encoding); TODO check this qualifying principle and add tests for it // TextEncodingDocument textEncoding = XmlHelper.substituteWithTextEncoding(encoding); // return new TextEncoderDecoder(textEncoding.getTextEncoding()); // } // // public static XmlEncoderDecoder createXmlEncoderDecoder(AbstractEncodingType encoding) { // XMLEncodingDocument xmlEncoding = XmlHelper.substituteWithXmlEncoding(encoding); // return new XmlEncoderDecoder(xmlEncoding.getXMLEncoding()); // } // // public static BinaryEncoderDecoder createBinaryEncoderDecoder(AbstractEncodingType encoding) { // BinaryEncodingDocument binaryEncoding = XmlHelper.substituteWithBinaryEncoding(encoding); // return new BinaryEncoderDecoder(binaryEncoding.getBinaryEncoding()); // } // // } // // /** // * @param toEncode // * the data representation to be encoded. // * @return the encoded data. // * @throws EncodingException // * if encoding fails. // */ // public E encode(T toEncode) throws EncodingException; // // /** // * @param toDecode // * a generic type representation to be decoded. // * @return the decoded data. // * @throws EncodingException // * if decoding fails. // */ // public T decode(E toDecode) throws EncodingException; // // /** // * @param toDecode // * an xml data representation to be decoded. // * @return the decoded data. // * @throws EncodingException // * if decoding fails. // */ // public T decode(XmlObject toDecode) throws EncodingException; // // }
import org.n52.sps.util.encoding.EncodingException; import org.n52.sps.util.encoding.SweEncoderDecoder; import net.opengis.swe.x20.XMLEncodingType; import org.apache.xmlbeans.XmlObject;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.util.encoding.xml; // TODO implement XmlEncoderDecoder public class XmlEncoderDecoder implements SweEncoderDecoder<Void, Void> { public static final String XML_ENCODING = "http://www.opengis.net/swe/2.0/XMLEncoding"; public XmlEncoderDecoder(XMLEncodingType xmlEncoding) { // TODO Auto-generated constructor stub }
// Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/EncodingException.java // public class EncodingException extends Exception { // // private static final long serialVersionUID = 6668408941898169625L; // // public EncodingException(String message, Throwable throwable) { // super(message, throwable); // } // // public EncodingException(String message) { // super(message); // } // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/SweEncoderDecoder.java // public interface SweEncoderDecoder<T, E> { // // public static class Factory { // // public static TextEncoderDecoder createTextEncoderDecoder(AbstractEncodingType encoding) { // // XmlHelper.qualifyWith(TextEncodingDocument.type, encoding); TODO check this qualifying principle and add tests for it // TextEncodingDocument textEncoding = XmlHelper.substituteWithTextEncoding(encoding); // return new TextEncoderDecoder(textEncoding.getTextEncoding()); // } // // public static XmlEncoderDecoder createXmlEncoderDecoder(AbstractEncodingType encoding) { // XMLEncodingDocument xmlEncoding = XmlHelper.substituteWithXmlEncoding(encoding); // return new XmlEncoderDecoder(xmlEncoding.getXMLEncoding()); // } // // public static BinaryEncoderDecoder createBinaryEncoderDecoder(AbstractEncodingType encoding) { // BinaryEncodingDocument binaryEncoding = XmlHelper.substituteWithBinaryEncoding(encoding); // return new BinaryEncoderDecoder(binaryEncoding.getBinaryEncoding()); // } // // } // // /** // * @param toEncode // * the data representation to be encoded. // * @return the encoded data. // * @throws EncodingException // * if encoding fails. // */ // public E encode(T toEncode) throws EncodingException; // // /** // * @param toDecode // * a generic type representation to be decoded. // * @return the decoded data. // * @throws EncodingException // * if decoding fails. // */ // public T decode(E toDecode) throws EncodingException; // // /** // * @param toDecode // * an xml data representation to be decoded. // * @return the decoded data. // * @throws EncodingException // * if decoding fails. // */ // public T decode(XmlObject toDecode) throws EncodingException; // // } // Path: 52n-sps-api/src/main/java/org/n52/sps/util/encoding/xml/XmlEncoderDecoder.java import org.n52.sps.util.encoding.EncodingException; import org.n52.sps.util.encoding.SweEncoderDecoder; import net.opengis.swe.x20.XMLEncodingType; import org.apache.xmlbeans.XmlObject; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.util.encoding.xml; // TODO implement XmlEncoderDecoder public class XmlEncoderDecoder implements SweEncoderDecoder<Void, Void> { public static final String XML_ENCODING = "http://www.opengis.net/swe/2.0/XMLEncoding"; public XmlEncoderDecoder(XMLEncodingType xmlEncoding) { // TODO Auto-generated constructor stub }
public Void encode(Void toEncode) throws EncodingException {
52North/SensorPlanningService
52n-sps-api/src/test/java/org/n52/sps/service/SpsComponentProviderTest.java
// Path: 52n-sps-api/src/test/java/org/n52/sps/service/core/BasicSensorPlannerMockup.java // public class BasicSensorPlannerMockup implements BasicSensorPlanner { // // private static final Logger LOGGER = LoggerFactory.getLogger(BasicSensorPlannerMockup.class); // // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings) { // LOGGER.info("Mockup: skipping interceptCapabilities"); // } // // public XmlObject describeResultAccess(DescribeResultAccessDocument describeResultAccess) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping describeResultAccess and return null"); // return null; // } // // public XmlObject describeTasking(DescribeTaskingDocument describeTasking) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping describeTasking and return null"); // return null; // } // // public XmlObject getCapabilities(GetCapabilitiesDocument getCapabilities) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getCapabilities and return null"); // return null; // } // // public XmlObject getStatus(GetStatusDocument getStatus) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getStatus and return null"); // return null; // } // // public XmlObject getTask(GetTaskDocument getTask) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getTask and return null"); // return null; // } // // public XmlObject submit(SubmitDocument submit) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping submit and return null"); // return null; // } // // } // // Path: 52n-sps-api/src/test/java/org/n52/sps/service/core/SensorProviderMockup.java // public class SensorProviderMockup implements SensorProvider { // // private static final Logger LOGGER = LoggerFactory.getLogger(SensorProviderMockup.class); // // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings) { // LOGGER.info("Mockup: skipping interceptCapabilities"); // } // // public DescribeSensorResponseDocument describeSensor(DescribeSensorDocument describeSensor) throws OwsException, // OwsExceptionReport { // LOGGER.info("Mockup: skipping describeSensor and return null"); // return null; // } // // }
import org.junit.Test; import org.n52.ows.exception.OwsException; import org.n52.sps.service.core.BasicSensorPlannerMockup; import org.n52.sps.service.core.SensorProviderMockup; import static org.junit.Assert.fail; import org.junit.Before;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service; public class SpsComponentProviderTest { private SpsComponentProvider spsComponentProvider; @Before public void setUp() throws Exception {
// Path: 52n-sps-api/src/test/java/org/n52/sps/service/core/BasicSensorPlannerMockup.java // public class BasicSensorPlannerMockup implements BasicSensorPlanner { // // private static final Logger LOGGER = LoggerFactory.getLogger(BasicSensorPlannerMockup.class); // // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings) { // LOGGER.info("Mockup: skipping interceptCapabilities"); // } // // public XmlObject describeResultAccess(DescribeResultAccessDocument describeResultAccess) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping describeResultAccess and return null"); // return null; // } // // public XmlObject describeTasking(DescribeTaskingDocument describeTasking) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping describeTasking and return null"); // return null; // } // // public XmlObject getCapabilities(GetCapabilitiesDocument getCapabilities) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getCapabilities and return null"); // return null; // } // // public XmlObject getStatus(GetStatusDocument getStatus) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getStatus and return null"); // return null; // } // // public XmlObject getTask(GetTaskDocument getTask) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getTask and return null"); // return null; // } // // public XmlObject submit(SubmitDocument submit) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping submit and return null"); // return null; // } // // } // // Path: 52n-sps-api/src/test/java/org/n52/sps/service/core/SensorProviderMockup.java // public class SensorProviderMockup implements SensorProvider { // // private static final Logger LOGGER = LoggerFactory.getLogger(SensorProviderMockup.class); // // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings) { // LOGGER.info("Mockup: skipping interceptCapabilities"); // } // // public DescribeSensorResponseDocument describeSensor(DescribeSensorDocument describeSensor) throws OwsException, // OwsExceptionReport { // LOGGER.info("Mockup: skipping describeSensor and return null"); // return null; // } // // } // Path: 52n-sps-api/src/test/java/org/n52/sps/service/SpsComponentProviderTest.java import org.junit.Test; import org.n52.ows.exception.OwsException; import org.n52.sps.service.core.BasicSensorPlannerMockup; import org.n52.sps.service.core.SensorProviderMockup; import static org.junit.Assert.fail; import org.junit.Before; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service; public class SpsComponentProviderTest { private SpsComponentProvider spsComponentProvider; @Before public void setUp() throws Exception {
spsComponentProvider = new SpsComponentProvider(new BasicSensorPlannerMockup(), new SensorProviderMockup());
52North/SensorPlanningService
52n-sps-api/src/test/java/org/n52/sps/service/SpsComponentProviderTest.java
// Path: 52n-sps-api/src/test/java/org/n52/sps/service/core/BasicSensorPlannerMockup.java // public class BasicSensorPlannerMockup implements BasicSensorPlanner { // // private static final Logger LOGGER = LoggerFactory.getLogger(BasicSensorPlannerMockup.class); // // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings) { // LOGGER.info("Mockup: skipping interceptCapabilities"); // } // // public XmlObject describeResultAccess(DescribeResultAccessDocument describeResultAccess) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping describeResultAccess and return null"); // return null; // } // // public XmlObject describeTasking(DescribeTaskingDocument describeTasking) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping describeTasking and return null"); // return null; // } // // public XmlObject getCapabilities(GetCapabilitiesDocument getCapabilities) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getCapabilities and return null"); // return null; // } // // public XmlObject getStatus(GetStatusDocument getStatus) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getStatus and return null"); // return null; // } // // public XmlObject getTask(GetTaskDocument getTask) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getTask and return null"); // return null; // } // // public XmlObject submit(SubmitDocument submit) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping submit and return null"); // return null; // } // // } // // Path: 52n-sps-api/src/test/java/org/n52/sps/service/core/SensorProviderMockup.java // public class SensorProviderMockup implements SensorProvider { // // private static final Logger LOGGER = LoggerFactory.getLogger(SensorProviderMockup.class); // // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings) { // LOGGER.info("Mockup: skipping interceptCapabilities"); // } // // public DescribeSensorResponseDocument describeSensor(DescribeSensorDocument describeSensor) throws OwsException, // OwsExceptionReport { // LOGGER.info("Mockup: skipping describeSensor and return null"); // return null; // } // // }
import org.junit.Test; import org.n52.ows.exception.OwsException; import org.n52.sps.service.core.BasicSensorPlannerMockup; import org.n52.sps.service.core.SensorProviderMockup; import static org.junit.Assert.fail; import org.junit.Before;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service; public class SpsComponentProviderTest { private SpsComponentProvider spsComponentProvider; @Before public void setUp() throws Exception {
// Path: 52n-sps-api/src/test/java/org/n52/sps/service/core/BasicSensorPlannerMockup.java // public class BasicSensorPlannerMockup implements BasicSensorPlanner { // // private static final Logger LOGGER = LoggerFactory.getLogger(BasicSensorPlannerMockup.class); // // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings) { // LOGGER.info("Mockup: skipping interceptCapabilities"); // } // // public XmlObject describeResultAccess(DescribeResultAccessDocument describeResultAccess) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping describeResultAccess and return null"); // return null; // } // // public XmlObject describeTasking(DescribeTaskingDocument describeTasking) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping describeTasking and return null"); // return null; // } // // public XmlObject getCapabilities(GetCapabilitiesDocument getCapabilities) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getCapabilities and return null"); // return null; // } // // public XmlObject getStatus(GetStatusDocument getStatus) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getStatus and return null"); // return null; // } // // public XmlObject getTask(GetTaskDocument getTask) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping getTask and return null"); // return null; // } // // public XmlObject submit(SubmitDocument submit) throws OwsException, OwsExceptionReport { // LOGGER.info("Mockup: skipping submit and return null"); // return null; // } // // } // // Path: 52n-sps-api/src/test/java/org/n52/sps/service/core/SensorProviderMockup.java // public class SensorProviderMockup implements SensorProvider { // // private static final Logger LOGGER = LoggerFactory.getLogger(SensorProviderMockup.class); // // public void interceptCapabilities(CapabilitiesType capabilities, List<HttpBinding> httpBindings) { // LOGGER.info("Mockup: skipping interceptCapabilities"); // } // // public DescribeSensorResponseDocument describeSensor(DescribeSensorDocument describeSensor) throws OwsException, // OwsExceptionReport { // LOGGER.info("Mockup: skipping describeSensor and return null"); // return null; // } // // } // Path: 52n-sps-api/src/test/java/org/n52/sps/service/SpsComponentProviderTest.java import org.junit.Test; import org.n52.ows.exception.OwsException; import org.n52.sps.service.core.BasicSensorPlannerMockup; import org.n52.sps.service.core.SensorProviderMockup; import static org.junit.Assert.fail; import org.junit.Before; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service; public class SpsComponentProviderTest { private SpsComponentProvider spsComponentProvider; @Before public void setUp() throws Exception {
spsComponentProvider = new SpsComponentProvider(new BasicSensorPlannerMockup(), new SensorProviderMockup());
52North/SensorPlanningService
52n-sps-api/src/test/java/org/n52/sps/sensor/model/SensorTaskTest.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/sensor/SensorTaskStatus.java // public enum SensorTaskStatus { // // CANCELLED(TaskStatusCodeEnumerationType.CANCELLED), // COMPLETED(TaskStatusCodeEnumerationType.COMPLETED), // EXPIRED(TaskStatusCodeEnumerationType.EXPIRED), // FAILED(TaskStatusCodeEnumerationType.FAILED), // INEXECUTION(TaskStatusCodeEnumerationType.IN_EXECUTION), // RESERVED(TaskStatusCodeEnumerationType.RESERVED); // // private TaskStatusCodeEnumerationType.Enum status; // // SensorTaskStatus(TaskStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static SensorTaskStatus getSensorTaskStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/TaskingRequestStatus.java // public enum TaskingRequestStatus { // // ACCEPTED(TaskingRequestStatusCodeEnumerationType.ACCEPTED), // PENDING(TaskingRequestStatusCodeEnumerationType.PENDING), // REJECTED(TaskingRequestStatusCodeEnumerationType.REJECTED); // // private TaskingRequestStatusCodeEnumerationType.Enum status; // // TaskingRequestStatus(TaskingRequestStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskingRequestStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static TaskingRequestStatus getTaskingRequestStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // }
import org.junit.Before; import org.junit.Test; import org.n52.sps.sensor.SensorTaskStatus; import org.n52.sps.tasking.TaskingRequestStatus; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.model; public class SensorTaskTest { private SensorTask validTask; private String taskId; private String procedure; @Before public void setUp() { procedure = "http://host.tld/procedure1/"; taskId = "http://host.tld/procedure1/tasks/1"; validTask = new SensorTask(taskId, procedure); } @Test(expected = IllegalArgumentException.class) public void testIllegalSensorTaskCreation() { new SensorTask(null, ""); } @Test public void testSensorTaskCreation() { assertPendingStateAftertaskCreation(); assertEquals(procedure, validTask.getProcedure()); assertEquals(taskId, validTask.getTaskId()); assertEquals("Pending", validTask.getRequestStatusAsString()); } private void assertPendingStateAftertaskCreation() {
// Path: 52n-sps-api/src/main/java/org/n52/sps/sensor/SensorTaskStatus.java // public enum SensorTaskStatus { // // CANCELLED(TaskStatusCodeEnumerationType.CANCELLED), // COMPLETED(TaskStatusCodeEnumerationType.COMPLETED), // EXPIRED(TaskStatusCodeEnumerationType.EXPIRED), // FAILED(TaskStatusCodeEnumerationType.FAILED), // INEXECUTION(TaskStatusCodeEnumerationType.IN_EXECUTION), // RESERVED(TaskStatusCodeEnumerationType.RESERVED); // // private TaskStatusCodeEnumerationType.Enum status; // // SensorTaskStatus(TaskStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static SensorTaskStatus getSensorTaskStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/TaskingRequestStatus.java // public enum TaskingRequestStatus { // // ACCEPTED(TaskingRequestStatusCodeEnumerationType.ACCEPTED), // PENDING(TaskingRequestStatusCodeEnumerationType.PENDING), // REJECTED(TaskingRequestStatusCodeEnumerationType.REJECTED); // // private TaskingRequestStatusCodeEnumerationType.Enum status; // // TaskingRequestStatus(TaskingRequestStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskingRequestStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static TaskingRequestStatus getTaskingRequestStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // } // Path: 52n-sps-api/src/test/java/org/n52/sps/sensor/model/SensorTaskTest.java import org.junit.Before; import org.junit.Test; import org.n52.sps.sensor.SensorTaskStatus; import org.n52.sps.tasking.TaskingRequestStatus; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.model; public class SensorTaskTest { private SensorTask validTask; private String taskId; private String procedure; @Before public void setUp() { procedure = "http://host.tld/procedure1/"; taskId = "http://host.tld/procedure1/tasks/1"; validTask = new SensorTask(taskId, procedure); } @Test(expected = IllegalArgumentException.class) public void testIllegalSensorTaskCreation() { new SensorTask(null, ""); } @Test public void testSensorTaskCreation() { assertPendingStateAftertaskCreation(); assertEquals(procedure, validTask.getProcedure()); assertEquals(taskId, validTask.getTaskId()); assertEquals("Pending", validTask.getRequestStatusAsString()); } private void assertPendingStateAftertaskCreation() {
boolean pendingTaskStatus = validTask.getRequestStatus().equals(TaskingRequestStatus.PENDING);
52North/SensorPlanningService
52n-sps-api/src/test/java/org/n52/sps/sensor/model/SensorTaskTest.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/sensor/SensorTaskStatus.java // public enum SensorTaskStatus { // // CANCELLED(TaskStatusCodeEnumerationType.CANCELLED), // COMPLETED(TaskStatusCodeEnumerationType.COMPLETED), // EXPIRED(TaskStatusCodeEnumerationType.EXPIRED), // FAILED(TaskStatusCodeEnumerationType.FAILED), // INEXECUTION(TaskStatusCodeEnumerationType.IN_EXECUTION), // RESERVED(TaskStatusCodeEnumerationType.RESERVED); // // private TaskStatusCodeEnumerationType.Enum status; // // SensorTaskStatus(TaskStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static SensorTaskStatus getSensorTaskStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/TaskingRequestStatus.java // public enum TaskingRequestStatus { // // ACCEPTED(TaskingRequestStatusCodeEnumerationType.ACCEPTED), // PENDING(TaskingRequestStatusCodeEnumerationType.PENDING), // REJECTED(TaskingRequestStatusCodeEnumerationType.REJECTED); // // private TaskingRequestStatusCodeEnumerationType.Enum status; // // TaskingRequestStatus(TaskingRequestStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskingRequestStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static TaskingRequestStatus getTaskingRequestStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // }
import org.junit.Before; import org.junit.Test; import org.n52.sps.sensor.SensorTaskStatus; import org.n52.sps.tasking.TaskingRequestStatus; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.model; public class SensorTaskTest { private SensorTask validTask; private String taskId; private String procedure; @Before public void setUp() { procedure = "http://host.tld/procedure1/"; taskId = "http://host.tld/procedure1/tasks/1"; validTask = new SensorTask(taskId, procedure); } @Test(expected = IllegalArgumentException.class) public void testIllegalSensorTaskCreation() { new SensorTask(null, ""); } @Test public void testSensorTaskCreation() { assertPendingStateAftertaskCreation(); assertEquals(procedure, validTask.getProcedure()); assertEquals(taskId, validTask.getTaskId()); assertEquals("Pending", validTask.getRequestStatusAsString()); } private void assertPendingStateAftertaskCreation() { boolean pendingTaskStatus = validTask.getRequestStatus().equals(TaskingRequestStatus.PENDING); assertTrue("SensorTask request status has to be in PENDING state directly after creation!", pendingTaskStatus); } @Test public void testGetTaskStatusAsString() {
// Path: 52n-sps-api/src/main/java/org/n52/sps/sensor/SensorTaskStatus.java // public enum SensorTaskStatus { // // CANCELLED(TaskStatusCodeEnumerationType.CANCELLED), // COMPLETED(TaskStatusCodeEnumerationType.COMPLETED), // EXPIRED(TaskStatusCodeEnumerationType.EXPIRED), // FAILED(TaskStatusCodeEnumerationType.FAILED), // INEXECUTION(TaskStatusCodeEnumerationType.IN_EXECUTION), // RESERVED(TaskStatusCodeEnumerationType.RESERVED); // // private TaskStatusCodeEnumerationType.Enum status; // // SensorTaskStatus(TaskStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static SensorTaskStatus getSensorTaskStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/tasking/TaskingRequestStatus.java // public enum TaskingRequestStatus { // // ACCEPTED(TaskingRequestStatusCodeEnumerationType.ACCEPTED), // PENDING(TaskingRequestStatusCodeEnumerationType.PENDING), // REJECTED(TaskingRequestStatusCodeEnumerationType.REJECTED); // // private TaskingRequestStatusCodeEnumerationType.Enum status; // // TaskingRequestStatus(TaskingRequestStatusCodeEnumerationType.Enum status) { // this.status = status; // } // // public TaskingRequestStatusCodeEnumerationType.Enum getStatus() { // return status; // } // // public static TaskingRequestStatus getTaskingRequestStatus(String status) { // return valueOf(status.toUpperCase()); // } // // @Override // public String toString() { // return status.toString(); // } // // } // Path: 52n-sps-api/src/test/java/org/n52/sps/sensor/model/SensorTaskTest.java import org.junit.Before; import org.junit.Test; import org.n52.sps.sensor.SensorTaskStatus; import org.n52.sps.tasking.TaskingRequestStatus; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.model; public class SensorTaskTest { private SensorTask validTask; private String taskId; private String procedure; @Before public void setUp() { procedure = "http://host.tld/procedure1/"; taskId = "http://host.tld/procedure1/tasks/1"; validTask = new SensorTask(taskId, procedure); } @Test(expected = IllegalArgumentException.class) public void testIllegalSensorTaskCreation() { new SensorTask(null, ""); } @Test public void testSensorTaskCreation() { assertPendingStateAftertaskCreation(); assertEquals(procedure, validTask.getProcedure()); assertEquals(taskId, validTask.getTaskId()); assertEquals("Pending", validTask.getRequestStatusAsString()); } private void assertPendingStateAftertaskCreation() { boolean pendingTaskStatus = validTask.getRequestStatus().equals(TaskingRequestStatus.PENDING); assertTrue("SensorTask request status has to be in PENDING state directly after creation!", pendingTaskStatus); } @Test public void testGetTaskStatusAsString() {
validTask.setTaskStatus(SensorTaskStatus.INEXECUTION);
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/sensor/result/DataNotAvailable.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/DataUnavailableCode.java // public enum DataUnavailableCode { // // DATA_NOT_AVAILABLE("DataNotAvailable"), // DATA_SERVICE_UNAVAILABLE("DataServiceUnavailable"); // // private String code; // // private DataUnavailableCode(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // }
import net.opengis.sps.x20.DescribeResultAccessResponseType.Availability.Unavailable; import org.n52.sps.service.core.DataUnavailableCode; import net.opengis.ows.x11.LanguageStringType; import net.opengis.sps.x20.DataNotAvailableType; import net.opengis.sps.x20.DescribeResultAccessResponseType.Availability;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.result; public final class DataNotAvailable implements ResultAccessAvailabilityDescriptor { private final Availability availability = Availability.Factory.newInstance(); public DataNotAvailable(LanguageStringType... messages) { Unavailable unavailable = availability.addNewUnavailable(); DataNotAvailableType dataNotAvailable = unavailable.addNewDataNotAvailable();
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/DataUnavailableCode.java // public enum DataUnavailableCode { // // DATA_NOT_AVAILABLE("DataNotAvailable"), // DATA_SERVICE_UNAVAILABLE("DataServiceUnavailable"); // // private String code; // // private DataUnavailableCode(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // } // Path: 52n-sps-api/src/main/java/org/n52/sps/sensor/result/DataNotAvailable.java import net.opengis.sps.x20.DescribeResultAccessResponseType.Availability.Unavailable; import org.n52.sps.service.core.DataUnavailableCode; import net.opengis.ows.x11.LanguageStringType; import net.opengis.sps.x20.DataNotAvailableType; import net.opengis.sps.x20.DescribeResultAccessResponseType.Availability; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.sensor.result; public final class DataNotAvailable implements ResultAccessAvailabilityDescriptor { private final Availability availability = Availability.Factory.newInstance(); public DataNotAvailable(LanguageStringType... messages) { Unavailable unavailable = availability.addNewUnavailable(); DataNotAvailableType dataNotAvailable = unavailable.addNewDataNotAvailable();
dataNotAvailable.setUnavailableCode(DataUnavailableCode.DATA_NOT_AVAILABLE.getCode());
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/service/admin/MissingSensorInformationException.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceException.java // public abstract class InternalServiceException extends Exception { // // private static final long serialVersionUID = -1598594769157092219L; // // public static final int BAD_REQUEST = 400; // // private List<String> detailedMessages = new ArrayList<String>(); // private String exceptionCode; // private String locator; // // public InternalServiceException(String exceptionCode, String locator) { // this.exceptionCode = exceptionCode; // this.locator = locator; // } // // public String getExceptionCode() { // return exceptionCode; // } // // public void setExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getLocator() { // return locator; // } // // public void setLocator(String locator) { // this.locator = locator; // } // // public void addDetailedMessage(String detailedMessage) { // detailedMessages.add(detailedMessage); // } // // public Iterable<String> getDetailedMessages() { // return detailedMessages; // } // // public abstract int getHttpStatusCode(); // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceExceptionCode.java // public enum InternalServiceExceptionCode { // // WRONG_PLUGIN_TYPE_RELATION("WrongPluginTypeRelation"), // MISSING_SENSOR_INFORMATION("MissingSensorInformation"), // UNKNOWN_SERVICE_INSTANCE("UnknownServiceInstance"); // // private String exceptionCode; // // private InternalServiceExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getExceptionCode() { // return exceptionCode; // } // }
import org.n52.sps.service.InternalServiceException; import org.n52.sps.service.InternalServiceExceptionCode;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.admin; public class MissingSensorInformationException extends InternalServiceException { private static final long serialVersionUID = -7661454857813095434L; public MissingSensorInformationException(String locator) {
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceException.java // public abstract class InternalServiceException extends Exception { // // private static final long serialVersionUID = -1598594769157092219L; // // public static final int BAD_REQUEST = 400; // // private List<String> detailedMessages = new ArrayList<String>(); // private String exceptionCode; // private String locator; // // public InternalServiceException(String exceptionCode, String locator) { // this.exceptionCode = exceptionCode; // this.locator = locator; // } // // public String getExceptionCode() { // return exceptionCode; // } // // public void setExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getLocator() { // return locator; // } // // public void setLocator(String locator) { // this.locator = locator; // } // // public void addDetailedMessage(String detailedMessage) { // detailedMessages.add(detailedMessage); // } // // public Iterable<String> getDetailedMessages() { // return detailedMessages; // } // // public abstract int getHttpStatusCode(); // // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/InternalServiceExceptionCode.java // public enum InternalServiceExceptionCode { // // WRONG_PLUGIN_TYPE_RELATION("WrongPluginTypeRelation"), // MISSING_SENSOR_INFORMATION("MissingSensorInformation"), // UNKNOWN_SERVICE_INSTANCE("UnknownServiceInstance"); // // private String exceptionCode; // // private InternalServiceExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getExceptionCode() { // return exceptionCode; // } // } // Path: 52n-sps-api/src/main/java/org/n52/sps/service/admin/MissingSensorInformationException.java import org.n52.sps.service.InternalServiceException; import org.n52.sps.service.InternalServiceExceptionCode; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.admin; public class MissingSensorInformationException extends InternalServiceException { private static final long serialVersionUID = -7661454857813095434L; public MissingSensorInformationException(String locator) {
super(InternalServiceExceptionCode.MISSING_SENSOR_INFORMATION.toString(), locator);
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/service/core/StatusInformationExpiredException.java
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/SpsExceptionCode.java // public enum SpsExceptionCode { // // STATUS_INFORMATION_EXPIRED("StatusInformationExpired"), // MODIFICATION_OF_FINALIZED_TASK("ModificationOfFinalizedTask"); // // private String exceptionCode; // // private SpsExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getExceptionCode() { // return exceptionCode; // } // }
import org.n52.ows.exception.OwsException; import org.n52.sps.service.SpsExceptionCode;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.core; /** * The service already discarded status information for the requested task / tasking request. */ public class StatusInformationExpiredException extends OwsException { private static final long serialVersionUID = 3330128800539226853L; public StatusInformationExpiredException() {
// Path: 52n-sps-api/src/main/java/org/n52/sps/service/SpsExceptionCode.java // public enum SpsExceptionCode { // // STATUS_INFORMATION_EXPIRED("StatusInformationExpired"), // MODIFICATION_OF_FINALIZED_TASK("ModificationOfFinalizedTask"); // // private String exceptionCode; // // private SpsExceptionCode(String exceptionCode) { // this.exceptionCode = exceptionCode; // } // // public String getExceptionCode() { // return exceptionCode; // } // } // Path: 52n-sps-api/src/main/java/org/n52/sps/service/core/StatusInformationExpiredException.java import org.n52.ows.exception.OwsException; import org.n52.sps.service.SpsExceptionCode; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.service.core; /** * The service already discarded status information for the requested task / tasking request. */ public class StatusInformationExpiredException extends OwsException { private static final long serialVersionUID = 3330128800539226853L; public StatusInformationExpiredException() {
super(SpsExceptionCode.STATUS_INFORMATION_EXPIRED.getExceptionCode());
52North/SensorPlanningService
52n-sps-webapp/src/main/java/org/n52/sps/control/xml/XmlValidationDelegate.java
// Path: 52n-sps-webapp/src/main/java/org/n52/sps/control/RequestDelegationHandler.java // public interface RequestDelegationHandler { // // /** // * Delegate request to corresponding SPS components. // * // * @return the service's response. // * @throws OwsException // * @see BasicSensorPlanner // * @see TaskUpdater // * @see TaskCanceller // * @see ReservationManager // * @see SensorDescriptionManager // * @see FeasibilityController // * @see SensorProvider // */ // public XmlObject delegate() throws OwsException, OwsExceptionReport; // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/SensorPlanningService.java // public interface SensorPlanningService { // // public static final String SPS_VERSION = "2.0.0"; // // public static final String OWS_VERSION = "1.1.0"; // // // mandatory // public BasicSensorPlanner getBasicSensorPlanner(); // // // mandatory // public SensorProvider getSensorProvider(); // // // optional // public FeasibilityController getFeasibilityController(); // // // optional // public ReservationManager getReservationManager(); // // // optional // public SensorDescriptionManager getSensorDescriptionManager(); // // // optional // public TaskCanceller getTaskCanceller(); // // // optional // public TaskUpdater getTaskUpdater(); // // // optional/custom // public SpsAdmin getSpsAdmin(); // // /** // * Method intiating a shutdown of all SPS components. // */ // public void shutdown(); // // public void validateGetCapabilitiesParameters(GetCapabilitiesDocument getCapabilities) throws OwsException; // // public void validateMandatoryServiceParameter(String serviceParameter) throws OwsException; // // public void validateVersionParameter(String version) throws OwsException; // // /** // * @param httpBinding supported DCP binding. // */ // public void addHttpBinding(HttpBinding httpBinding); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/FeasibilityController profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingFeasibilityControllerProfile(); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/ReservationManager profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingReservationManagerProfile(); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/SensorHistoryProvider profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingSensorHistoryProviderProfile(); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/TaskCanceller profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingTaskCancellerProfile(); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/TaskUpdater profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingTaskUpdaterProfile(); // // // /** // * @return <code>true</code> if an SPS administratin interface is available. // */ // public boolean isSpsAdminAvailable(); // // /** // * Intercepts the passed {@link CapabilitiesDocument} with service related setup (e.g. OperationsMetadata, supported Profiles, etc.) info. // * // * @param capabilities the capabilities to intercept. // */ // public void interceptCapabilities(CapabilitiesDocument capabilities); // // // }
import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; import org.n52.ows.exception.OwsException; import org.n52.ows.exception.OwsExceptionReport; import org.n52.oxf.swes.exception.InvalidRequestException; import org.n52.oxf.xmlbeans.SwesXmlUtil; import org.n52.sps.control.RequestDelegationHandler; import org.n52.sps.service.SensorPlanningService; import javax.xml.namespace.QName; import net.opengis.sps.x20.GetCapabilitiesDocument;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.control.xml; public class XmlValidationDelegate implements RequestDelegationHandler { private XmlDelegate requestHandler;
// Path: 52n-sps-webapp/src/main/java/org/n52/sps/control/RequestDelegationHandler.java // public interface RequestDelegationHandler { // // /** // * Delegate request to corresponding SPS components. // * // * @return the service's response. // * @throws OwsException // * @see BasicSensorPlanner // * @see TaskUpdater // * @see TaskCanceller // * @see ReservationManager // * @see SensorDescriptionManager // * @see FeasibilityController // * @see SensorProvider // */ // public XmlObject delegate() throws OwsException, OwsExceptionReport; // // } // // Path: 52n-sps-api/src/main/java/org/n52/sps/service/SensorPlanningService.java // public interface SensorPlanningService { // // public static final String SPS_VERSION = "2.0.0"; // // public static final String OWS_VERSION = "1.1.0"; // // // mandatory // public BasicSensorPlanner getBasicSensorPlanner(); // // // mandatory // public SensorProvider getSensorProvider(); // // // optional // public FeasibilityController getFeasibilityController(); // // // optional // public ReservationManager getReservationManager(); // // // optional // public SensorDescriptionManager getSensorDescriptionManager(); // // // optional // public TaskCanceller getTaskCanceller(); // // // optional // public TaskUpdater getTaskUpdater(); // // // optional/custom // public SpsAdmin getSpsAdmin(); // // /** // * Method intiating a shutdown of all SPS components. // */ // public void shutdown(); // // public void validateGetCapabilitiesParameters(GetCapabilitiesDocument getCapabilities) throws OwsException; // // public void validateMandatoryServiceParameter(String serviceParameter) throws OwsException; // // public void validateVersionParameter(String version) throws OwsException; // // /** // * @param httpBinding supported DCP binding. // */ // public void addHttpBinding(HttpBinding httpBinding); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/FeasibilityController profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingFeasibilityControllerProfile(); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/ReservationManager profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingReservationManagerProfile(); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/SensorHistoryProvider profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingSensorHistoryProviderProfile(); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/TaskCanceller profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingTaskCancellerProfile(); // // /** // * @return <code>true</code> if http://www.opengis.net/spec/SPS/2.0/conf/TaskUpdater profile is supported, <code>false</code> otherwise. // */ // public boolean isSupportingTaskUpdaterProfile(); // // // /** // * @return <code>true</code> if an SPS administratin interface is available. // */ // public boolean isSpsAdminAvailable(); // // /** // * Intercepts the passed {@link CapabilitiesDocument} with service related setup (e.g. OperationsMetadata, supported Profiles, etc.) info. // * // * @param capabilities the capabilities to intercept. // */ // public void interceptCapabilities(CapabilitiesDocument capabilities); // // // } // Path: 52n-sps-webapp/src/main/java/org/n52/sps/control/xml/XmlValidationDelegate.java import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; import org.n52.ows.exception.OwsException; import org.n52.ows.exception.OwsExceptionReport; import org.n52.oxf.swes.exception.InvalidRequestException; import org.n52.oxf.xmlbeans.SwesXmlUtil; import org.n52.sps.control.RequestDelegationHandler; import org.n52.sps.service.SensorPlanningService; import javax.xml.namespace.QName; import net.opengis.sps.x20.GetCapabilitiesDocument; /** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program 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 General Public License for more details. */ package org.n52.sps.control.xml; public class XmlValidationDelegate implements RequestDelegationHandler { private XmlDelegate requestHandler;
private SensorPlanningService service;
danfickle/cpp-to-java-source-converter
src/main/java/com/github/danfickle/cpptojavasourceconverter/GlobalCtx.java
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppClass extends CppDeclaration // { // public boolean isNested; // public boolean isUnion; // public String superclass; // public List<String> additionalSupers = new ArrayList<String>(0); // public List<CppDeclaration> declarations = new ArrayList<CppDeclaration>(); // // @Override // public String toString() // { // String str = this.isUnion ? String.format("\n%s/* TODO union */", tabOut()) : ""; // // str += String.format("\n%spublic%s class %s %s implements CppType<%s>", // tabOut(), // this.isNested ? " static" : "", // this.name, // this.superclass != null ? "extends " + this.superclass : "", // this.name); // // str += "\n" + tabOut() + '{'; // ctx.tabLevel++; // str += join(this.declarations, ""); // ctx.tabLevel--; // str += "\n" + tabOut() + '}'; // // return str; // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public abstract static class CppDeclaration // { // // The raw qualified (if needed) C++ name. // public String completeCppName; // // // The simple Java name. // public String name; // // public CppClass parent; // public IType cppType; // public IASTName nm; // public String file; // public int line; // }
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 com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppClass; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppDeclaration;
package com.github.danfickle.cpptojavasourceconverter; class GlobalCtx { // Items which need to be persisted accross translation // units should go here. int anonCount = 0; // A set of qualified names containing the bitfields... Set<String> bitfields = new HashSet<String>(); // Maps the type to a declaration. // Note, this is not a hash map as IType does // not implement hash method. Therefore it must // be iterated and checked with IType::isSameType method. // Note: Generated declarations are not required to go in // here as they are not called directly.
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppClass extends CppDeclaration // { // public boolean isNested; // public boolean isUnion; // public String superclass; // public List<String> additionalSupers = new ArrayList<String>(0); // public List<CppDeclaration> declarations = new ArrayList<CppDeclaration>(); // // @Override // public String toString() // { // String str = this.isUnion ? String.format("\n%s/* TODO union */", tabOut()) : ""; // // str += String.format("\n%spublic%s class %s %s implements CppType<%s>", // tabOut(), // this.isNested ? " static" : "", // this.name, // this.superclass != null ? "extends " + this.superclass : "", // this.name); // // str += "\n" + tabOut() + '{'; // ctx.tabLevel++; // str += join(this.declarations, ""); // ctx.tabLevel--; // str += "\n" + tabOut() + '}'; // // return str; // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public abstract static class CppDeclaration // { // // The raw qualified (if needed) C++ name. // public String completeCppName; // // // The simple Java name. // public String name; // // public CppClass parent; // public IType cppType; // public IASTName nm; // public String file; // public int line; // } // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/GlobalCtx.java 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 com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppClass; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppDeclaration; package com.github.danfickle.cpptojavasourceconverter; class GlobalCtx { // Items which need to be persisted accross translation // units should go here. int anonCount = 0; // A set of qualified names containing the bitfields... Set<String> bitfields = new HashSet<String>(); // Maps the type to a declaration. // Note, this is not a hash map as IType does // not implement hash method. Therefore it must // be iterated and checked with IType::isSameType method. // Note: Generated declarations are not required to go in // here as they are not called directly.
List<CppDeclaration> decls = new ArrayList<CppDeclaration>();
danfickle/cpp-to-java-source-converter
src/main/java/com/github/danfickle/cpptojavasourceconverter/GlobalCtx.java
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppClass extends CppDeclaration // { // public boolean isNested; // public boolean isUnion; // public String superclass; // public List<String> additionalSupers = new ArrayList<String>(0); // public List<CppDeclaration> declarations = new ArrayList<CppDeclaration>(); // // @Override // public String toString() // { // String str = this.isUnion ? String.format("\n%s/* TODO union */", tabOut()) : ""; // // str += String.format("\n%spublic%s class %s %s implements CppType<%s>", // tabOut(), // this.isNested ? " static" : "", // this.name, // this.superclass != null ? "extends " + this.superclass : "", // this.name); // // str += "\n" + tabOut() + '{'; // ctx.tabLevel++; // str += join(this.declarations, ""); // ctx.tabLevel--; // str += "\n" + tabOut() + '}'; // // return str; // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public abstract static class CppDeclaration // { // // The raw qualified (if needed) C++ name. // public String completeCppName; // // // The simple Java name. // public String name; // // public CppClass parent; // public IType cppType; // public IASTName nm; // public String file; // public int line; // }
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 com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppClass; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppDeclaration;
package com.github.danfickle.cpptojavasourceconverter; class GlobalCtx { // Items which need to be persisted accross translation // units should go here. int anonCount = 0; // A set of qualified names containing the bitfields... Set<String> bitfields = new HashSet<String>(); // Maps the type to a declaration. // Note, this is not a hash map as IType does // not implement hash method. Therefore it must // be iterated and checked with IType::isSameType method. // Note: Generated declarations are not required to go in // here as they are not called directly. List<CppDeclaration> decls = new ArrayList<CppDeclaration>(); // This contains a mapping from filenames to a generated global // declaration for that file which will house global items such // as variables and functions.
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppClass extends CppDeclaration // { // public boolean isNested; // public boolean isUnion; // public String superclass; // public List<String> additionalSupers = new ArrayList<String>(0); // public List<CppDeclaration> declarations = new ArrayList<CppDeclaration>(); // // @Override // public String toString() // { // String str = this.isUnion ? String.format("\n%s/* TODO union */", tabOut()) : ""; // // str += String.format("\n%spublic%s class %s %s implements CppType<%s>", // tabOut(), // this.isNested ? " static" : "", // this.name, // this.superclass != null ? "extends " + this.superclass : "", // this.name); // // str += "\n" + tabOut() + '{'; // ctx.tabLevel++; // str += join(this.declarations, ""); // ctx.tabLevel--; // str += "\n" + tabOut() + '}'; // // return str; // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public abstract static class CppDeclaration // { // // The raw qualified (if needed) C++ name. // public String completeCppName; // // // The simple Java name. // public String name; // // public CppClass parent; // public IType cppType; // public IASTName nm; // public String file; // public int line; // } // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/GlobalCtx.java 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 com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppClass; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppDeclaration; package com.github.danfickle.cpptojavasourceconverter; class GlobalCtx { // Items which need to be persisted accross translation // units should go here. int anonCount = 0; // A set of qualified names containing the bitfields... Set<String> bitfields = new HashSet<String>(); // Maps the type to a declaration. // Note, this is not a hash map as IType does // not implement hash method. Therefore it must // be iterated and checked with IType::isSameType method. // Note: Generated declarations are not required to go in // here as they are not called directly. List<CppDeclaration> decls = new ArrayList<CppDeclaration>(); // This contains a mapping from filenames to a generated global // declaration for that file which will house global items such // as variables and functions.
Map<String, CppClass> fileClasses = new HashMap<String, CppClass>();
danfickle/cpp-to-java-source-converter
src/main/java/com/github/danfickle/cpptojavasourceconverter/helper/SampleOutput.java
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/helper/Template.java // public static enum UnaryOp // { // opAmper, // opMinus, // opPlus, // opLogicalNot, // opPostIncrement, // opPostDecrement, // opPreIncrement, // opPreDecrement, // opStar, // opComplement; // }
import com.github.danfickle.cpptojavasourceconverter.helper.Template.UnaryOp;
package com.github.danfickle.cpptojavasourceconverter.helper; class SampleOutput { @SuppressWarnings("unused") void ptrNumberSample() { IInteger i = MInteger.valueOf(0); // int i; IInteger j = i.addressOf(); // int * j = &i; IInteger k = j.ptrCopy(); // int * k = j; IInteger l = MIntegerMulti.create(24); // int l[24]; IInteger m = l.ptrOffset(2).addressOf(); // int * m = &l[2]; IInteger n = l.ptrCopy(); // int * n = l; IInteger o = MInteger.valueOf(l.ptrOffset(5).get()); //int o = l[5]; or int o = *(l + 5); } @SuppressWarnings("unused") void templateSample() { IInteger i = MInteger.valueOf(10); // int i = 10; Object j = i; // Replicate template conditions.
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/helper/Template.java // public static enum UnaryOp // { // opAmper, // opMinus, // opPlus, // opLogicalNot, // opPostIncrement, // opPostDecrement, // opPreIncrement, // opPreDecrement, // opStar, // opComplement; // } // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/helper/SampleOutput.java import com.github.danfickle.cpptojavasourceconverter.helper.Template.UnaryOp; package com.github.danfickle.cpptojavasourceconverter.helper; class SampleOutput { @SuppressWarnings("unused") void ptrNumberSample() { IInteger i = MInteger.valueOf(0); // int i; IInteger j = i.addressOf(); // int * j = &i; IInteger k = j.ptrCopy(); // int * k = j; IInteger l = MIntegerMulti.create(24); // int l[24]; IInteger m = l.ptrOffset(2).addressOf(); // int * m = &l[2]; IInteger n = l.ptrCopy(); // int * n = l; IInteger o = MInteger.valueOf(l.ptrOffset(5).get()); //int o = l[5]; or int o = *(l + 5); } @SuppressWarnings("unused") void templateSample() { IInteger i = MInteger.valueOf(10); // int i = 10; Object j = i; // Replicate template conditions.
Object k = Template.doUnaryOp(j, UnaryOp.opMinus);
danfickle/cpp-to-java-source-converter
src/main/java/com/github/danfickle/cpptojavasourceconverter/models/StmtModels.java
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TranslationUnitContext.java // public class TranslationUnitContext // { // SourceConverter converter; // StackManager stackMngr; // ExpressionEvaluator exprEvaluator; // StmtEvaluator stmtEvaluator; // BitfieldManager bitfieldMngr; // EnumManager enumMngr; // FunctionManager funcMngr; // SpecialGenerator specialGenerator; // InitializationManager initMngr; // TypeManager typeMngr; // GlobalCtx global; // StmtModels stmtModels; // public DeclarationModels declModels; // public int tabLevel; // // String currentFileName; // IType currentReturnType; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class MSimpleDecl extends CppDeclaration // { // public boolean isStatic; // public String type; // public MExpression initExpr; // public boolean isPublic; // // @Override // public String toString() // { // // public [static] type name [= expr]; // if (this.isPublic) // { // return String.format("%spublic %s %s %s%s%s;", // tabOut(), // this.isStatic ? " static" : "", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // else // { // // type name [= expr] // return String.format("%s %s%s%s", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/ExpressionModels.java // public abstract static class MExpression // {}
import java.util.ArrayList; import java.util.List; import com.github.danfickle.cpptojavasourceconverter.TranslationUnitContext; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.MSimpleDecl; import com.github.danfickle.cpptojavasourceconverter.models.ExpressionModels.MExpression;
package com.github.danfickle.cpptojavasourceconverter.models; public class StmtModels {
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TranslationUnitContext.java // public class TranslationUnitContext // { // SourceConverter converter; // StackManager stackMngr; // ExpressionEvaluator exprEvaluator; // StmtEvaluator stmtEvaluator; // BitfieldManager bitfieldMngr; // EnumManager enumMngr; // FunctionManager funcMngr; // SpecialGenerator specialGenerator; // InitializationManager initMngr; // TypeManager typeMngr; // GlobalCtx global; // StmtModels stmtModels; // public DeclarationModels declModels; // public int tabLevel; // // String currentFileName; // IType currentReturnType; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class MSimpleDecl extends CppDeclaration // { // public boolean isStatic; // public String type; // public MExpression initExpr; // public boolean isPublic; // // @Override // public String toString() // { // // public [static] type name [= expr]; // if (this.isPublic) // { // return String.format("%spublic %s %s %s%s%s;", // tabOut(), // this.isStatic ? " static" : "", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // else // { // // type name [= expr] // return String.format("%s %s%s%s", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/ExpressionModels.java // public abstract static class MExpression // {} // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/StmtModels.java import java.util.ArrayList; import java.util.List; import com.github.danfickle.cpptojavasourceconverter.TranslationUnitContext; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.MSimpleDecl; import com.github.danfickle.cpptojavasourceconverter.models.ExpressionModels.MExpression; package com.github.danfickle.cpptojavasourceconverter.models; public class StmtModels {
private TranslationUnitContext ctx;
danfickle/cpp-to-java-source-converter
src/main/java/com/github/danfickle/cpptojavasourceconverter/models/StmtModels.java
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TranslationUnitContext.java // public class TranslationUnitContext // { // SourceConverter converter; // StackManager stackMngr; // ExpressionEvaluator exprEvaluator; // StmtEvaluator stmtEvaluator; // BitfieldManager bitfieldMngr; // EnumManager enumMngr; // FunctionManager funcMngr; // SpecialGenerator specialGenerator; // InitializationManager initMngr; // TypeManager typeMngr; // GlobalCtx global; // StmtModels stmtModels; // public DeclarationModels declModels; // public int tabLevel; // // String currentFileName; // IType currentReturnType; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class MSimpleDecl extends CppDeclaration // { // public boolean isStatic; // public String type; // public MExpression initExpr; // public boolean isPublic; // // @Override // public String toString() // { // // public [static] type name [= expr]; // if (this.isPublic) // { // return String.format("%spublic %s %s %s%s%s;", // tabOut(), // this.isStatic ? " static" : "", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // else // { // // type name [= expr] // return String.format("%s %s%s%s", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/ExpressionModels.java // public abstract static class MExpression // {}
import java.util.ArrayList; import java.util.List; import com.github.danfickle.cpptojavasourceconverter.TranslationUnitContext; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.MSimpleDecl; import com.github.danfickle.cpptojavasourceconverter.models.ExpressionModels.MExpression;
ctx.tabLevel -= addTabs; return ret; } private String tabOut() { return tabOut(0); } private String tabOut(Object child) { if (child == null || child instanceof MCompoundStmt) return ""; return tabOut(0); } private String stripNl(String str) { if (str.endsWith("\n")) return str.substring(0, str.length() - 1); return str; } public abstract static class MStmt {} public class MForStmt extends MStmt { public MStmt initializer;
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TranslationUnitContext.java // public class TranslationUnitContext // { // SourceConverter converter; // StackManager stackMngr; // ExpressionEvaluator exprEvaluator; // StmtEvaluator stmtEvaluator; // BitfieldManager bitfieldMngr; // EnumManager enumMngr; // FunctionManager funcMngr; // SpecialGenerator specialGenerator; // InitializationManager initMngr; // TypeManager typeMngr; // GlobalCtx global; // StmtModels stmtModels; // public DeclarationModels declModels; // public int tabLevel; // // String currentFileName; // IType currentReturnType; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class MSimpleDecl extends CppDeclaration // { // public boolean isStatic; // public String type; // public MExpression initExpr; // public boolean isPublic; // // @Override // public String toString() // { // // public [static] type name [= expr]; // if (this.isPublic) // { // return String.format("%spublic %s %s %s%s%s;", // tabOut(), // this.isStatic ? " static" : "", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // else // { // // type name [= expr] // return String.format("%s %s%s%s", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/ExpressionModels.java // public abstract static class MExpression // {} // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/StmtModels.java import java.util.ArrayList; import java.util.List; import com.github.danfickle.cpptojavasourceconverter.TranslationUnitContext; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.MSimpleDecl; import com.github.danfickle.cpptojavasourceconverter.models.ExpressionModels.MExpression; ctx.tabLevel -= addTabs; return ret; } private String tabOut() { return tabOut(0); } private String tabOut(Object child) { if (child == null || child instanceof MCompoundStmt) return ""; return tabOut(0); } private String stripNl(String str) { if (str.endsWith("\n")) return str.substring(0, str.length() - 1); return str; } public abstract static class MStmt {} public class MForStmt extends MStmt { public MStmt initializer;
public MExpression condition;
danfickle/cpp-to-java-source-converter
src/main/java/com/github/danfickle/cpptojavasourceconverter/models/StmtModels.java
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TranslationUnitContext.java // public class TranslationUnitContext // { // SourceConverter converter; // StackManager stackMngr; // ExpressionEvaluator exprEvaluator; // StmtEvaluator stmtEvaluator; // BitfieldManager bitfieldMngr; // EnumManager enumMngr; // FunctionManager funcMngr; // SpecialGenerator specialGenerator; // InitializationManager initMngr; // TypeManager typeMngr; // GlobalCtx global; // StmtModels stmtModels; // public DeclarationModels declModels; // public int tabLevel; // // String currentFileName; // IType currentReturnType; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class MSimpleDecl extends CppDeclaration // { // public boolean isStatic; // public String type; // public MExpression initExpr; // public boolean isPublic; // // @Override // public String toString() // { // // public [static] type name [= expr]; // if (this.isPublic) // { // return String.format("%spublic %s %s %s%s%s;", // tabOut(), // this.isStatic ? " static" : "", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // else // { // // type name [= expr] // return String.format("%s %s%s%s", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/ExpressionModels.java // public abstract static class MExpression // {}
import java.util.ArrayList; import java.util.List; import com.github.danfickle.cpptojavasourceconverter.TranslationUnitContext; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.MSimpleDecl; import com.github.danfickle.cpptojavasourceconverter.models.ExpressionModels.MExpression;
} private String tabOut() { return tabOut(0); } private String tabOut(Object child) { if (child == null || child instanceof MCompoundStmt) return ""; return tabOut(0); } private String stripNl(String str) { if (str.endsWith("\n")) return str.substring(0, str.length() - 1); return str; } public abstract static class MStmt {} public class MForStmt extends MStmt { public MStmt initializer; public MExpression condition; public MExpression updater;
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TranslationUnitContext.java // public class TranslationUnitContext // { // SourceConverter converter; // StackManager stackMngr; // ExpressionEvaluator exprEvaluator; // StmtEvaluator stmtEvaluator; // BitfieldManager bitfieldMngr; // EnumManager enumMngr; // FunctionManager funcMngr; // SpecialGenerator specialGenerator; // InitializationManager initMngr; // TypeManager typeMngr; // GlobalCtx global; // StmtModels stmtModels; // public DeclarationModels declModels; // public int tabLevel; // // String currentFileName; // IType currentReturnType; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class MSimpleDecl extends CppDeclaration // { // public boolean isStatic; // public String type; // public MExpression initExpr; // public boolean isPublic; // // @Override // public String toString() // { // // public [static] type name [= expr]; // if (this.isPublic) // { // return String.format("%spublic %s %s %s%s%s;", // tabOut(), // this.isStatic ? " static" : "", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // else // { // // type name [= expr] // return String.format("%s %s%s%s", // this.type, this.name, // this.initExpr != null ? " = " : "", // this.initExpr != null ? this.initExpr : ""); // } // } // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/ExpressionModels.java // public abstract static class MExpression // {} // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/StmtModels.java import java.util.ArrayList; import java.util.List; import com.github.danfickle.cpptojavasourceconverter.TranslationUnitContext; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.MSimpleDecl; import com.github.danfickle.cpptojavasourceconverter.models.ExpressionModels.MExpression; } private String tabOut() { return tabOut(0); } private String tabOut(Object child) { if (child == null || child instanceof MCompoundStmt) return ""; return tabOut(0); } private String stripNl(String str) { if (str.endsWith("\n")) return str.substring(0, str.length() - 1); return str; } public abstract static class MStmt {} public class MForStmt extends MStmt { public MStmt initializer; public MExpression condition; public MExpression updater;
public MSimpleDecl decl;
danfickle/cpp-to-java-source-converter
src/main/java/com/github/danfickle/cpptojavasourceconverter/BitfieldManager.java
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum NameType // { // CAPITALIZED, // CAMEL_CASE, // ALL_CAPS; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum TypeType // { // INTERFACE, // IMPLEMENTATION, // RAW; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppBitfield extends CppDeclaration // { // public String qualified; // public String type; // public MExpression bits; // // @Override // public String toString() // { // /* // int gettest_with_bit_field() // { // return bitfields & 1 // } // // int settest_with_bit_field(final int val) // { // bitfields &= ~1; // bitfields |= (val << 0) & 1; // return val; // } // // int postInctest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret + 1) // } // // int postDectest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret - 1) // } // */ // // StringBuilder sb = new StringBuilder(); // // sb.append(String.format("\n%s%s get%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sreturn bitfields & 1", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s set%s(final %s val)", tabOut(), this.type, this.name, this.type)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sbitfields &= ~1;", tabOut(1))); // sb.append(String.format("\n%sbitfields |= (val << 0) & 1;", tabOut(1))); // sb.append(String.format("\n%sreturn val;", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postInc%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret + 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postDec%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret - 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // return sb.toString(); // } // }
import org.eclipse.cdt.core.dom.ast.*; import com.github.danfickle.cpptojavasourceconverter.TypeManager.NameType; import com.github.danfickle.cpptojavasourceconverter.TypeManager.TypeType; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppBitfield;
package com.github.danfickle.cpptojavasourceconverter; public class BitfieldManager { private TranslationUnitContext ctx; BitfieldManager(TranslationUnitContext con) { ctx = con; } boolean isBitfield(IASTName name) throws DOMException { String complete = TypeManager.getCompleteName(name); return ctx.global.bitfields.contains(complete); } void addBitfield(IASTName name) throws DOMException { String complete = TypeManager.getCompleteName(name); ctx.global.bitfields.add(complete); } boolean isBitfield(IASTExpression expr) throws DOMException { expr = ExpressionHelpers.unwrap(expr); if (expr instanceof IASTIdExpression && isBitfield(((IASTIdExpression) expr).getName())) return true; if (expr instanceof IASTFieldReference && isBitfield(((IASTFieldReference) expr).getFieldName())) return true; return false; } void evalDeclBitfield(IField field, IASTDeclarator declarator) throws DOMException {
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum NameType // { // CAPITALIZED, // CAMEL_CASE, // ALL_CAPS; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum TypeType // { // INTERFACE, // IMPLEMENTATION, // RAW; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppBitfield extends CppDeclaration // { // public String qualified; // public String type; // public MExpression bits; // // @Override // public String toString() // { // /* // int gettest_with_bit_field() // { // return bitfields & 1 // } // // int settest_with_bit_field(final int val) // { // bitfields &= ~1; // bitfields |= (val << 0) & 1; // return val; // } // // int postInctest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret + 1) // } // // int postDectest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret - 1) // } // */ // // StringBuilder sb = new StringBuilder(); // // sb.append(String.format("\n%s%s get%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sreturn bitfields & 1", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s set%s(final %s val)", tabOut(), this.type, this.name, this.type)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sbitfields &= ~1;", tabOut(1))); // sb.append(String.format("\n%sbitfields |= (val << 0) & 1;", tabOut(1))); // sb.append(String.format("\n%sreturn val;", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postInc%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret + 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postDec%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret - 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // return sb.toString(); // } // } // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/BitfieldManager.java import org.eclipse.cdt.core.dom.ast.*; import com.github.danfickle.cpptojavasourceconverter.TypeManager.NameType; import com.github.danfickle.cpptojavasourceconverter.TypeManager.TypeType; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppBitfield; package com.github.danfickle.cpptojavasourceconverter; public class BitfieldManager { private TranslationUnitContext ctx; BitfieldManager(TranslationUnitContext con) { ctx = con; } boolean isBitfield(IASTName name) throws DOMException { String complete = TypeManager.getCompleteName(name); return ctx.global.bitfields.contains(complete); } void addBitfield(IASTName name) throws DOMException { String complete = TypeManager.getCompleteName(name); ctx.global.bitfields.add(complete); } boolean isBitfield(IASTExpression expr) throws DOMException { expr = ExpressionHelpers.unwrap(expr); if (expr instanceof IASTIdExpression && isBitfield(((IASTIdExpression) expr).getName())) return true; if (expr instanceof IASTFieldReference && isBitfield(((IASTFieldReference) expr).getFieldName())) return true; return false; } void evalDeclBitfield(IField field, IASTDeclarator declarator) throws DOMException {
CppBitfield bitfield = ctx.declModels.new CppBitfield();
danfickle/cpp-to-java-source-converter
src/main/java/com/github/danfickle/cpptojavasourceconverter/BitfieldManager.java
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum NameType // { // CAPITALIZED, // CAMEL_CASE, // ALL_CAPS; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum TypeType // { // INTERFACE, // IMPLEMENTATION, // RAW; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppBitfield extends CppDeclaration // { // public String qualified; // public String type; // public MExpression bits; // // @Override // public String toString() // { // /* // int gettest_with_bit_field() // { // return bitfields & 1 // } // // int settest_with_bit_field(final int val) // { // bitfields &= ~1; // bitfields |= (val << 0) & 1; // return val; // } // // int postInctest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret + 1) // } // // int postDectest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret - 1) // } // */ // // StringBuilder sb = new StringBuilder(); // // sb.append(String.format("\n%s%s get%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sreturn bitfields & 1", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s set%s(final %s val)", tabOut(), this.type, this.name, this.type)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sbitfields &= ~1;", tabOut(1))); // sb.append(String.format("\n%sbitfields |= (val << 0) & 1;", tabOut(1))); // sb.append(String.format("\n%sreturn val;", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postInc%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret + 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postDec%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret - 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // return sb.toString(); // } // }
import org.eclipse.cdt.core.dom.ast.*; import com.github.danfickle.cpptojavasourceconverter.TypeManager.NameType; import com.github.danfickle.cpptojavasourceconverter.TypeManager.TypeType; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppBitfield;
{ String complete = TypeManager.getCompleteName(name); return ctx.global.bitfields.contains(complete); } void addBitfield(IASTName name) throws DOMException { String complete = TypeManager.getCompleteName(name); ctx.global.bitfields.add(complete); } boolean isBitfield(IASTExpression expr) throws DOMException { expr = ExpressionHelpers.unwrap(expr); if (expr instanceof IASTIdExpression && isBitfield(((IASTIdExpression) expr).getName())) return true; if (expr instanceof IASTFieldReference && isBitfield(((IASTFieldReference) expr).getFieldName())) return true; return false; } void evalDeclBitfield(IField field, IASTDeclarator declarator) throws DOMException { CppBitfield bitfield = ctx.declModels.new CppBitfield(); addBitfield(declarator.getName());
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum NameType // { // CAPITALIZED, // CAMEL_CASE, // ALL_CAPS; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum TypeType // { // INTERFACE, // IMPLEMENTATION, // RAW; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppBitfield extends CppDeclaration // { // public String qualified; // public String type; // public MExpression bits; // // @Override // public String toString() // { // /* // int gettest_with_bit_field() // { // return bitfields & 1 // } // // int settest_with_bit_field(final int val) // { // bitfields &= ~1; // bitfields |= (val << 0) & 1; // return val; // } // // int postInctest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret + 1) // } // // int postDectest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret - 1) // } // */ // // StringBuilder sb = new StringBuilder(); // // sb.append(String.format("\n%s%s get%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sreturn bitfields & 1", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s set%s(final %s val)", tabOut(), this.type, this.name, this.type)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sbitfields &= ~1;", tabOut(1))); // sb.append(String.format("\n%sbitfields |= (val << 0) & 1;", tabOut(1))); // sb.append(String.format("\n%sreturn val;", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postInc%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret + 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postDec%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret - 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // return sb.toString(); // } // } // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/BitfieldManager.java import org.eclipse.cdt.core.dom.ast.*; import com.github.danfickle.cpptojavasourceconverter.TypeManager.NameType; import com.github.danfickle.cpptojavasourceconverter.TypeManager.TypeType; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppBitfield; { String complete = TypeManager.getCompleteName(name); return ctx.global.bitfields.contains(complete); } void addBitfield(IASTName name) throws DOMException { String complete = TypeManager.getCompleteName(name); ctx.global.bitfields.add(complete); } boolean isBitfield(IASTExpression expr) throws DOMException { expr = ExpressionHelpers.unwrap(expr); if (expr instanceof IASTIdExpression && isBitfield(((IASTIdExpression) expr).getName())) return true; if (expr instanceof IASTFieldReference && isBitfield(((IASTFieldReference) expr).getFieldName())) return true; return false; } void evalDeclBitfield(IField field, IASTDeclarator declarator) throws DOMException { CppBitfield bitfield = ctx.declModels.new CppBitfield(); addBitfield(declarator.getName());
bitfield.name = TypeManager.cppNameToJavaName(field.getName(), NameType.CAMEL_CASE);
danfickle/cpp-to-java-source-converter
src/main/java/com/github/danfickle/cpptojavasourceconverter/BitfieldManager.java
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum NameType // { // CAPITALIZED, // CAMEL_CASE, // ALL_CAPS; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum TypeType // { // INTERFACE, // IMPLEMENTATION, // RAW; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppBitfield extends CppDeclaration // { // public String qualified; // public String type; // public MExpression bits; // // @Override // public String toString() // { // /* // int gettest_with_bit_field() // { // return bitfields & 1 // } // // int settest_with_bit_field(final int val) // { // bitfields &= ~1; // bitfields |= (val << 0) & 1; // return val; // } // // int postInctest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret + 1) // } // // int postDectest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret - 1) // } // */ // // StringBuilder sb = new StringBuilder(); // // sb.append(String.format("\n%s%s get%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sreturn bitfields & 1", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s set%s(final %s val)", tabOut(), this.type, this.name, this.type)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sbitfields &= ~1;", tabOut(1))); // sb.append(String.format("\n%sbitfields |= (val << 0) & 1;", tabOut(1))); // sb.append(String.format("\n%sreturn val;", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postInc%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret + 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postDec%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret - 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // return sb.toString(); // } // }
import org.eclipse.cdt.core.dom.ast.*; import com.github.danfickle.cpptojavasourceconverter.TypeManager.NameType; import com.github.danfickle.cpptojavasourceconverter.TypeManager.TypeType; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppBitfield;
return ctx.global.bitfields.contains(complete); } void addBitfield(IASTName name) throws DOMException { String complete = TypeManager.getCompleteName(name); ctx.global.bitfields.add(complete); } boolean isBitfield(IASTExpression expr) throws DOMException { expr = ExpressionHelpers.unwrap(expr); if (expr instanceof IASTIdExpression && isBitfield(((IASTIdExpression) expr).getName())) return true; if (expr instanceof IASTFieldReference && isBitfield(((IASTFieldReference) expr).getFieldName())) return true; return false; } void evalDeclBitfield(IField field, IASTDeclarator declarator) throws DOMException { CppBitfield bitfield = ctx.declModels.new CppBitfield(); addBitfield(declarator.getName()); bitfield.name = TypeManager.cppNameToJavaName(field.getName(), NameType.CAMEL_CASE); bitfield.bits = ctx.exprEvaluator.eval1Expr(((IASTFieldDeclarator) declarator).getBitFieldSize());
// Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum NameType // { // CAPITALIZED, // CAMEL_CASE, // ALL_CAPS; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/TypeManager.java // enum TypeType // { // INTERFACE, // IMPLEMENTATION, // RAW; // } // // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/models/DeclarationModels.java // public class CppBitfield extends CppDeclaration // { // public String qualified; // public String type; // public MExpression bits; // // @Override // public String toString() // { // /* // int gettest_with_bit_field() // { // return bitfields & 1 // } // // int settest_with_bit_field(final int val) // { // bitfields &= ~1; // bitfields |= (val << 0) & 1; // return val; // } // // int postInctest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret + 1) // } // // int postDectest_with_bit_field() // { // int ret = gettest_with_bit_field(); // settest_with_bit_field(ret - 1) // } // */ // // StringBuilder sb = new StringBuilder(); // // sb.append(String.format("\n%s%s get%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sreturn bitfields & 1", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s set%s(final %s val)", tabOut(), this.type, this.name, this.type)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sbitfields &= ~1;", tabOut(1))); // sb.append(String.format("\n%sbitfields |= (val << 0) & 1;", tabOut(1))); // sb.append(String.format("\n%sreturn val;", tabOut(1))); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postInc%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret + 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // sb.append(String.format("\n\n%s%s postDec%s()", tabOut(), this.type, this.name)); // sb.append(String.format("\n%s{", tabOut())); // sb.append(String.format("\n%sint ret = get%s();", tabOut(1), this.name)); // sb.append(String.format("\n%sset%s(ret - 1)", tabOut(1), this.name)); // sb.append(String.format("\n%s}", tabOut())); // // return sb.toString(); // } // } // Path: src/main/java/com/github/danfickle/cpptojavasourceconverter/BitfieldManager.java import org.eclipse.cdt.core.dom.ast.*; import com.github.danfickle.cpptojavasourceconverter.TypeManager.NameType; import com.github.danfickle.cpptojavasourceconverter.TypeManager.TypeType; import com.github.danfickle.cpptojavasourceconverter.models.DeclarationModels.CppBitfield; return ctx.global.bitfields.contains(complete); } void addBitfield(IASTName name) throws DOMException { String complete = TypeManager.getCompleteName(name); ctx.global.bitfields.add(complete); } boolean isBitfield(IASTExpression expr) throws DOMException { expr = ExpressionHelpers.unwrap(expr); if (expr instanceof IASTIdExpression && isBitfield(((IASTIdExpression) expr).getName())) return true; if (expr instanceof IASTFieldReference && isBitfield(((IASTFieldReference) expr).getFieldName())) return true; return false; } void evalDeclBitfield(IField field, IASTDeclarator declarator) throws DOMException { CppBitfield bitfield = ctx.declModels.new CppBitfield(); addBitfield(declarator.getName()); bitfield.name = TypeManager.cppNameToJavaName(field.getName(), NameType.CAMEL_CASE); bitfield.bits = ctx.exprEvaluator.eval1Expr(((IASTFieldDeclarator) declarator).getBitFieldSize());
bitfield.type = ctx.typeMngr.cppToJavaType(field.getType(), TypeType.RAW);
kebernet/pretty
src/test/java/com/reachcall/pretty/config/ResolverTest.java
// Path: src/main/java/com/reachcall/pretty/config/Configurator.java // public static interface ConfiguratorCallback { // Configuration activeConfiguration(); // // void onLoad(Configuration configuration); // }
import com.reachcall.pretty.config.Configurator.ConfiguratorCallback; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBException; import org.junit.Test; import static org.junit.Assert.assertEquals;
/** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ package com.reachcall.pretty.config; /** * * @author kebernet */ public class ResolverTest { public ResolverTest() { } @Test public void testGetActiveConfiguration() throws JAXBException, InterruptedException { final Resolver r = new Resolver(null, 500);
// Path: src/main/java/com/reachcall/pretty/config/Configurator.java // public static interface ConfiguratorCallback { // Configuration activeConfiguration(); // // void onLoad(Configuration configuration); // } // Path: src/test/java/com/reachcall/pretty/config/ResolverTest.java import com.reachcall.pretty.config.Configurator.ConfiguratorCallback; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBException; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ package com.reachcall.pretty.config; /** * * @author kebernet */ public class ResolverTest { public ResolverTest() { } @Test public void testGetActiveConfiguration() throws JAXBException, InterruptedException { final Resolver r = new Resolver(null, 500);
Configurator configurator = new Configurator( new ConfiguratorCallback(){
kebernet/pretty
src/test/java/com/reachcall/pretty/config/ConfigurationTest.java
// Path: src/main/java/com/reachcall/pretty/config/Configurator.java // public static interface ConfiguratorCallback { // Configuration activeConfiguration(); // // void onLoad(Configuration configuration); // }
import com.reachcall.pretty.config.Configurator.ConfiguratorCallback; import java.io.File; import javax.xml.bind.JAXBException; import org.junit.Test; import static org.junit.Assert.assertEquals;
/** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ package com.reachcall.pretty.config; /** * * @author kebernet */ public class ConfigurationTest { public ConfigurationTest() { } /** * Test of setChildren method, of class Configuration. */ @Test public void testSimple() throws JAXBException { System.out.println("testSimple"); final Configuration[] holder = new Configuration[1];
// Path: src/main/java/com/reachcall/pretty/config/Configurator.java // public static interface ConfiguratorCallback { // Configuration activeConfiguration(); // // void onLoad(Configuration configuration); // } // Path: src/test/java/com/reachcall/pretty/config/ConfigurationTest.java import com.reachcall.pretty.config.Configurator.ConfiguratorCallback; import java.io.File; import javax.xml.bind.JAXBException; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ package com.reachcall.pretty.config; /** * * @author kebernet */ public class ConfigurationTest { public ConfigurationTest() { } /** * Test of setChildren method, of class Configuration. */ @Test public void testSimple() throws JAXBException { System.out.println("testSimple"); final Configuration[] holder = new Configuration[1];
Configurator c = new Configurator(new ConfiguratorCallback(){
kebernet/pretty
src/main/java/com/reachcall/pretty/websocket/ProxyWebSocket.java
// Path: src/main/java/com/reachcall/pretty/config/Match.java // public class Match { // public final Configuration rootConfiguration; // public final Path path; // public final String finalPath; // public Destination destination; // public String affinityId; // // public Match(final String affinityId, final Path path, // final String finalPath, final Configuration rootConfiguration) { // this.affinityId = affinityId; // this.path = path; // this.finalPath = finalPath; // this.rootConfiguration = rootConfiguration; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (getClass() != obj.getClass()) { // return false; // } // // final Match other = (Match) obj; // // if ((this.finalPath == null) ? (other.finalPath != null) // : (!this.finalPath.equals( // other.finalPath))) { // return false; // } // // if ((this.destination != other.destination) // && ((this.destination == null) // || !this.destination.equals(other.destination))) { // return false; // } // // if ((this.affinityId == null) ? (other.affinityId != null) // : (!this.affinityId.equals( // other.affinityId))) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // int hash = 3; // hash = (13 * hash) // + ((this.finalPath != null) ? this.finalPath.hashCode() : 0); // hash = (13 * hash) // + ((this.destination != null) ? this.destination.hashCode() : 0); // hash = (13 * hash) // + ((this.affinityId != null) ? this.affinityId.hashCode() : 0); // // return hash; // } // // public String toURL(){ // return "http://"+this.destination.getHost()+":"+this.destination.getPort()+ (finalPath.startsWith("/") ? finalPath : "/"+finalPath); // } // }
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.reachcall.pretty.config.Match; import org.eclipse.jetty.websocket.WebSocket; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest;
/** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ package com.reachcall.pretty.websocket; /** * */ public class ProxyWebSocket implements WebSocket, WebSocket.OnFrame { private static final Logger LOG = Logger.getLogger(ProxyWebSocket.class.getCanonicalName()); private Connection connection;
// Path: src/main/java/com/reachcall/pretty/config/Match.java // public class Match { // public final Configuration rootConfiguration; // public final Path path; // public final String finalPath; // public Destination destination; // public String affinityId; // // public Match(final String affinityId, final Path path, // final String finalPath, final Configuration rootConfiguration) { // this.affinityId = affinityId; // this.path = path; // this.finalPath = finalPath; // this.rootConfiguration = rootConfiguration; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (getClass() != obj.getClass()) { // return false; // } // // final Match other = (Match) obj; // // if ((this.finalPath == null) ? (other.finalPath != null) // : (!this.finalPath.equals( // other.finalPath))) { // return false; // } // // if ((this.destination != other.destination) // && ((this.destination == null) // || !this.destination.equals(other.destination))) { // return false; // } // // if ((this.affinityId == null) ? (other.affinityId != null) // : (!this.affinityId.equals( // other.affinityId))) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // int hash = 3; // hash = (13 * hash) // + ((this.finalPath != null) ? this.finalPath.hashCode() : 0); // hash = (13 * hash) // + ((this.destination != null) ? this.destination.hashCode() : 0); // hash = (13 * hash) // + ((this.affinityId != null) ? this.affinityId.hashCode() : 0); // // return hash; // } // // public String toURL(){ // return "http://"+this.destination.getHost()+":"+this.destination.getPort()+ (finalPath.startsWith("/") ? finalPath : "/"+finalPath); // } // } // Path: src/main/java/com/reachcall/pretty/websocket/ProxyWebSocket.java import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.reachcall.pretty.config.Match; import org.eclipse.jetty.websocket.WebSocket; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; /** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ package com.reachcall.pretty.websocket; /** * */ public class ProxyWebSocket implements WebSocket, WebSocket.OnFrame { private static final Logger LOG = Logger.getLogger(ProxyWebSocket.class.getCanonicalName()); private Connection connection;
private final Match destination;
kebernet/pretty
src/main/java/com/reachcall/pretty/TLSSetup.java
// Path: src/main/java/com/reachcall/util/ImportKey.java // public class ImportKey { // /** // * <p>Creates an InputStream from a file, and fills it with the complete // * file. Thus, available() on the returned InputStream will return the // * full number of bytes the file contains</p> // * @param fname The filename // * @return The filled InputStream // * @exception IOException, if the Streams couldn't be created. // **/ // private static InputStream fullStream(String fname) // throws IOException { // FileInputStream fis = new FileInputStream(fname); // DataInputStream dis = new DataInputStream(fis); // byte[] bytes = new byte[dis.available()]; // dis.readFully(bytes); // // ByteArrayInputStream bais = new ByteArrayInputStream(bytes); // // return bais; // } // // /** // * <p>Takes two file names for a key and the certificate for the key, // * and imports those into a keystore. Optionally it takes an alias // * for the key. // * <p>The first argument is the filename for the key. The key should be // * in PKCS8-format. // * <p>The second argument is the filename for the certificate for the key. // * <p>If a third argument is given it is used as the alias. If missing, // * the key is imported with the alias importkey // * <p>The name of the keystore file can be controlled by setting // * the keystore property (java -Dkeystore=mykeystore). If no name // * is given, the file is named <code>keystore.ImportKey</code> // * and placed in your home directory. // * @param args [0] Name of the key file, [1] Name of the certificate file // * [2] Alias for the key. // **/ // public static void main(String[] args) { // // change this if you want another password by default // String keypass = "importkey"; // // // change this if you want another alias by default // String defaultalias = "importkey"; // // // change this if you want another keystorefile by default // String keystorename = System.getProperty("keystore"); // // if (keystorename == null) { // keystorename = System.getProperty("user.home") + System.getProperty("file.separator") + // "keystore.ImportKey"; // especially this ;-) // } // // // parsing command line input // String keyfile = ""; // String certfile = ""; // // if ((args.length < 2) || (args.length > 3)) { // System.out.println("Usage: java comu.ImportKey keyfile certfile [alias]"); // System.exit(0); // } else { // keyfile = args[0]; // certfile = args[1]; // // if (args.length > 2) { // defaultalias = args[2]; // } // } // importKey(keypass, keystorename, keyfile, certfile, defaultalias); // } // // public static void importKey(String keypass, String keystorename, String keyfile, String certfile, String defaultalias) { // try { // // initializing and clearing keystore // KeyStore ks = KeyStore.getInstance("JKS", "SUN"); // ks.load(null, keypass.toCharArray()); // System.out.println("Using keystore-file : " + keystorename); // ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); // ks.load(new FileInputStream(keystorename), keypass.toCharArray()); // // // loading Key // InputStream fl = fullStream(keyfile); // byte[] key = new byte[fl.available()]; // KeyFactory kf = KeyFactory.getInstance("RSA"); // fl.read(key, 0, fl.available()); // fl.close(); // // PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key); // PrivateKey ff = kf.generatePrivate(keysp); // // // loading CertificateChain // CertificateFactory cf = CertificateFactory.getInstance("X.509"); // InputStream certstream = fullStream(certfile); // // Collection c = cf.generateCertificates(certstream); // Certificate[] certs = new Certificate[c.toArray().length]; // // if (c.size() == 1) { // certstream = fullStream(certfile); // System.out.println("One certificate, no chain."); // // Certificate cert = cf.generateCertificate(certstream); // certs[0] = cert; // } else { // System.out.println("Certificate chain length: " + c.size()); // certs = (Certificate[]) c.toArray(); // } // // // storing keystore // ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs); // System.out.println("Key and certificate stored."); // System.out.println("Alias:" + defaultalias + " Password:" + keypass); // ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); // } catch (Exception ex) { // ex.printStackTrace(); // } // } // }
import com.reachcall.util.ImportKey; import java.io.File; import java.io.IOException; import com.beust.jcommander.JCommander;
"-outform", "DER"); b.inheritIO(); Process proc = b.start(); int exitCode = proc.waitFor(); if(exitCode != 0){ throw new RuntimeException("Conversion of key to der failed. Exit code: "+0); } return result; } private static File certPemToDer(File certPem) throws IOException, InterruptedException{ File result = File.createTempFile("certFile", "der"); result.deleteOnExit(); //openssl x509 -in cert.pem -inform PEM -out cert.der -outform DE ProcessBuilder b = new ProcessBuilder("openssl", "x509", "-in", certPem.getAbsolutePath(), "-inform", "PEM", "-out", result.getAbsolutePath(), "-outform", "DER"); b.inheritIO(); Process proc = b.start(); int exitCode = proc.waitFor(); if(exitCode != 0){ throw new RuntimeException("Conversion of certificate to der failed. Exit code: "+0); } return result; } private static void doImport(File keystoreFile, String keystorePassword, String alias, File keyFile, File certFile){
// Path: src/main/java/com/reachcall/util/ImportKey.java // public class ImportKey { // /** // * <p>Creates an InputStream from a file, and fills it with the complete // * file. Thus, available() on the returned InputStream will return the // * full number of bytes the file contains</p> // * @param fname The filename // * @return The filled InputStream // * @exception IOException, if the Streams couldn't be created. // **/ // private static InputStream fullStream(String fname) // throws IOException { // FileInputStream fis = new FileInputStream(fname); // DataInputStream dis = new DataInputStream(fis); // byte[] bytes = new byte[dis.available()]; // dis.readFully(bytes); // // ByteArrayInputStream bais = new ByteArrayInputStream(bytes); // // return bais; // } // // /** // * <p>Takes two file names for a key and the certificate for the key, // * and imports those into a keystore. Optionally it takes an alias // * for the key. // * <p>The first argument is the filename for the key. The key should be // * in PKCS8-format. // * <p>The second argument is the filename for the certificate for the key. // * <p>If a third argument is given it is used as the alias. If missing, // * the key is imported with the alias importkey // * <p>The name of the keystore file can be controlled by setting // * the keystore property (java -Dkeystore=mykeystore). If no name // * is given, the file is named <code>keystore.ImportKey</code> // * and placed in your home directory. // * @param args [0] Name of the key file, [1] Name of the certificate file // * [2] Alias for the key. // **/ // public static void main(String[] args) { // // change this if you want another password by default // String keypass = "importkey"; // // // change this if you want another alias by default // String defaultalias = "importkey"; // // // change this if you want another keystorefile by default // String keystorename = System.getProperty("keystore"); // // if (keystorename == null) { // keystorename = System.getProperty("user.home") + System.getProperty("file.separator") + // "keystore.ImportKey"; // especially this ;-) // } // // // parsing command line input // String keyfile = ""; // String certfile = ""; // // if ((args.length < 2) || (args.length > 3)) { // System.out.println("Usage: java comu.ImportKey keyfile certfile [alias]"); // System.exit(0); // } else { // keyfile = args[0]; // certfile = args[1]; // // if (args.length > 2) { // defaultalias = args[2]; // } // } // importKey(keypass, keystorename, keyfile, certfile, defaultalias); // } // // public static void importKey(String keypass, String keystorename, String keyfile, String certfile, String defaultalias) { // try { // // initializing and clearing keystore // KeyStore ks = KeyStore.getInstance("JKS", "SUN"); // ks.load(null, keypass.toCharArray()); // System.out.println("Using keystore-file : " + keystorename); // ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); // ks.load(new FileInputStream(keystorename), keypass.toCharArray()); // // // loading Key // InputStream fl = fullStream(keyfile); // byte[] key = new byte[fl.available()]; // KeyFactory kf = KeyFactory.getInstance("RSA"); // fl.read(key, 0, fl.available()); // fl.close(); // // PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key); // PrivateKey ff = kf.generatePrivate(keysp); // // // loading CertificateChain // CertificateFactory cf = CertificateFactory.getInstance("X.509"); // InputStream certstream = fullStream(certfile); // // Collection c = cf.generateCertificates(certstream); // Certificate[] certs = new Certificate[c.toArray().length]; // // if (c.size() == 1) { // certstream = fullStream(certfile); // System.out.println("One certificate, no chain."); // // Certificate cert = cf.generateCertificate(certstream); // certs[0] = cert; // } else { // System.out.println("Certificate chain length: " + c.size()); // certs = (Certificate[]) c.toArray(); // } // // // storing keystore // ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs); // System.out.println("Key and certificate stored."); // System.out.println("Alias:" + defaultalias + " Password:" + keypass); // ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // Path: src/main/java/com/reachcall/pretty/TLSSetup.java import com.reachcall.util.ImportKey; import java.io.File; import java.io.IOException; import com.beust.jcommander.JCommander; "-outform", "DER"); b.inheritIO(); Process proc = b.start(); int exitCode = proc.waitFor(); if(exitCode != 0){ throw new RuntimeException("Conversion of key to der failed. Exit code: "+0); } return result; } private static File certPemToDer(File certPem) throws IOException, InterruptedException{ File result = File.createTempFile("certFile", "der"); result.deleteOnExit(); //openssl x509 -in cert.pem -inform PEM -out cert.der -outform DE ProcessBuilder b = new ProcessBuilder("openssl", "x509", "-in", certPem.getAbsolutePath(), "-inform", "PEM", "-out", result.getAbsolutePath(), "-outform", "DER"); b.inheritIO(); Process proc = b.start(); int exitCode = proc.waitFor(); if(exitCode != 0){ throw new RuntimeException("Conversion of certificate to der failed. Exit code: "+0); } return result; } private static void doImport(File keystoreFile, String keystorePassword, String alias, File keyFile, File certFile){
ImportKey.importKey(keystorePassword, keystoreFile.getAbsolutePath(),keyFile.getAbsolutePath(), certFile.getAbsolutePath(), alias );
kebernet/pretty
src/test/java/com/reachcall/pretty/config/ConfiguratorTest.java
// Path: src/main/java/com/reachcall/pretty/config/Configurator.java // public static interface ConfiguratorCallback { // Configuration activeConfiguration(); // // void onLoad(Configuration configuration); // }
import com.reachcall.pretty.config.Configurator.ConfiguratorCallback; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import javax.xml.bind.JAXBException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.BeforeClass;
/** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ package com.reachcall.pretty.config; /** * * @author kebernet */ public class ConfiguratorTest { public ConfiguratorTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of setConfigFile method, of class Configurator. */ @Test public void testSimple() throws JAXBException { System.out.println("testSimple"); File newconfigFile = new File("target/pretty-config.xml"); final Configuration config = new Configuration(); config.setHostPattern(".*"); Path p = new Path(); p.setSource("/*"); p.setDestination("/"); ArrayList<Path> paths = new ArrayList<Path>(); paths.add(p); config.setPaths(paths);
// Path: src/main/java/com/reachcall/pretty/config/Configurator.java // public static interface ConfiguratorCallback { // Configuration activeConfiguration(); // // void onLoad(Configuration configuration); // } // Path: src/test/java/com/reachcall/pretty/config/ConfiguratorTest.java import com.reachcall.pretty.config.Configurator.ConfiguratorCallback; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import javax.xml.bind.JAXBException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.BeforeClass; /** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ package com.reachcall.pretty.config; /** * * @author kebernet */ public class ConfiguratorTest { public ConfiguratorTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of setConfigFile method, of class Configurator. */ @Test public void testSimple() throws JAXBException { System.out.println("testSimple"); File newconfigFile = new File("target/pretty-config.xml"); final Configuration config = new Configuration(); config.setHostPattern(".*"); Path p = new Path(); p.setSource("/*"); p.setDestination("/"); ArrayList<Path> paths = new ArrayList<Path>(); paths.add(p); config.setPaths(paths);
Configurator configurator = new Configurator(new ConfiguratorCallback(){
kebernet/pretty
src/test/java/com/reachcall/pretty/peering/FailWatcherTest.java
// Path: src/main/java/com/reachcall/pretty/peering/Agent.java // public static interface AgentListener { // // void onConfiguration(Configuration config); // // void onHeartbeat(Object remote); // } // // Path: src/main/java/com/reachcall/pretty/peering/beats/Heartbeat.java // public class Heartbeat implements Serializable { // // // // public final String instanceName; // public final long timestamp; // // public Heartbeat(String instanceName){ // this.instanceName = instanceName; // this.timestamp = System.currentTimeMillis(); // } // // @Override // public String toString() { // return "HB "+instanceName+" @ "+timestamp; // } // // }
import com.reachcall.pretty.peering.Agent.AgentListener; import com.reachcall.pretty.peering.beats.Heartbeat; import java.io.Serializable; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test;
/** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.reachcall.pretty.peering; /** * * @author robert.cooper */ public class FailWatcherTest { public FailWatcherTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } /** * Test of onHeartbeat method, of class FailWatcher. */ @Test public void testOnHeartbeat() throws Exception { System.out.println("--------------------------------------watcher test");
// Path: src/main/java/com/reachcall/pretty/peering/Agent.java // public static interface AgentListener { // // void onConfiguration(Configuration config); // // void onHeartbeat(Object remote); // } // // Path: src/main/java/com/reachcall/pretty/peering/beats/Heartbeat.java // public class Heartbeat implements Serializable { // // // // public final String instanceName; // public final long timestamp; // // public Heartbeat(String instanceName){ // this.instanceName = instanceName; // this.timestamp = System.currentTimeMillis(); // } // // @Override // public String toString() { // return "HB "+instanceName+" @ "+timestamp; // } // // } // Path: src/test/java/com/reachcall/pretty/peering/FailWatcherTest.java import com.reachcall.pretty.peering.Agent.AgentListener; import com.reachcall.pretty.peering.beats.Heartbeat; import java.io.Serializable; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.reachcall.pretty.peering; /** * * @author robert.cooper */ public class FailWatcherTest { public FailWatcherTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } /** * Test of onHeartbeat method, of class FailWatcher. */ @Test public void testOnHeartbeat() throws Exception { System.out.println("--------------------------------------watcher test");
final AgentListener[] listener = new AgentListener[1];
kebernet/pretty
src/test/java/com/reachcall/pretty/peering/FailWatcherTest.java
// Path: src/main/java/com/reachcall/pretty/peering/Agent.java // public static interface AgentListener { // // void onConfiguration(Configuration config); // // void onHeartbeat(Object remote); // } // // Path: src/main/java/com/reachcall/pretty/peering/beats/Heartbeat.java // public class Heartbeat implements Serializable { // // // // public final String instanceName; // public final long timestamp; // // public Heartbeat(String instanceName){ // this.instanceName = instanceName; // this.timestamp = System.currentTimeMillis(); // } // // @Override // public String toString() { // return "HB "+instanceName+" @ "+timestamp; // } // // }
import com.reachcall.pretty.peering.Agent.AgentListener; import com.reachcall.pretty.peering.beats.Heartbeat; import java.io.Serializable; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test;
/** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.reachcall.pretty.peering; /** * * @author robert.cooper */ public class FailWatcherTest { public FailWatcherTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } /** * Test of onHeartbeat method, of class FailWatcher. */ @Test public void testOnHeartbeat() throws Exception { System.out.println("--------------------------------------watcher test"); final AgentListener[] listener = new AgentListener[1]; Agent a = new Agent(6767){ @Override public void addListener(AgentListener l) { super.addListener(l); listener[0] = l; } @Override public void sendHeartbeat(Serializable object) { super.sendHeartbeat(object); System.out.println(object); } }; a.start(); FailWatcher watcher = new FailWatcher(a); watcher.setTimeToFailure(1000); watcher.start();
// Path: src/main/java/com/reachcall/pretty/peering/Agent.java // public static interface AgentListener { // // void onConfiguration(Configuration config); // // void onHeartbeat(Object remote); // } // // Path: src/main/java/com/reachcall/pretty/peering/beats/Heartbeat.java // public class Heartbeat implements Serializable { // // // // public final String instanceName; // public final long timestamp; // // public Heartbeat(String instanceName){ // this.instanceName = instanceName; // this.timestamp = System.currentTimeMillis(); // } // // @Override // public String toString() { // return "HB "+instanceName+" @ "+timestamp; // } // // } // Path: src/test/java/com/reachcall/pretty/peering/FailWatcherTest.java import com.reachcall.pretty.peering.Agent.AgentListener; import com.reachcall.pretty.peering.beats.Heartbeat; import java.io.Serializable; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.reachcall.pretty.peering; /** * * @author robert.cooper */ public class FailWatcherTest { public FailWatcherTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } /** * Test of onHeartbeat method, of class FailWatcher. */ @Test public void testOnHeartbeat() throws Exception { System.out.println("--------------------------------------watcher test"); final AgentListener[] listener = new AgentListener[1]; Agent a = new Agent(6767){ @Override public void addListener(AgentListener l) { super.addListener(l); listener[0] = l; } @Override public void sendHeartbeat(Serializable object) { super.sendHeartbeat(object); System.out.println(object); } }; a.start(); FailWatcher watcher = new FailWatcher(a); watcher.setTimeToFailure(1000); watcher.start();
a.sendHeartbeat(new Heartbeat("fake-host"));
kebernet/pretty
src/main/java/com/reachcall/pretty/peering/Heart.java
// Path: src/main/java/com/reachcall/pretty/peering/beats/Heartbeat.java // public class Heartbeat implements Serializable { // // // // public final String instanceName; // public final long timestamp; // // public Heartbeat(String instanceName){ // this.instanceName = instanceName; // this.timestamp = System.currentTimeMillis(); // } // // @Override // public String toString() { // return "HB "+instanceName+" @ "+timestamp; // } // // }
import com.reachcall.pretty.peering.beats.Heartbeat; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Timer; import java.util.TimerTask;
/** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.reachcall.pretty.peering; /** * * @author robert.cooper */ public class Heart { private String hostname; private Timer timer; private Agent agent; public Heart(Agent agent) throws UnknownHostException { this(null, agent); } public Heart(String hostname, Agent agent) throws UnknownHostException { this.hostname = (hostname == null) ? getHostname() : hostname; this.agent = agent; } private String getHostname() throws UnknownHostException { InetAddress addr = InetAddress.getLocalHost(); return addr.getHostName(); }
// Path: src/main/java/com/reachcall/pretty/peering/beats/Heartbeat.java // public class Heartbeat implements Serializable { // // // // public final String instanceName; // public final long timestamp; // // public Heartbeat(String instanceName){ // this.instanceName = instanceName; // this.timestamp = System.currentTimeMillis(); // } // // @Override // public String toString() { // return "HB "+instanceName+" @ "+timestamp; // } // // } // Path: src/main/java/com/reachcall/pretty/peering/Heart.java import com.reachcall.pretty.peering.beats.Heartbeat; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Timer; import java.util.TimerTask; /** * Copyright 2013, Robert Cooper, Reach Health * * 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 */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.reachcall.pretty.peering; /** * * @author robert.cooper */ public class Heart { private String hostname; private Timer timer; private Agent agent; public Heart(Agent agent) throws UnknownHostException { this(null, agent); } public Heart(String hostname, Agent agent) throws UnknownHostException { this.hostname = (hostname == null) ? getHostname() : hostname; this.agent = agent; } private String getHostname() throws UnknownHostException { InetAddress addr = InetAddress.getLocalHost(); return addr.getHostName(); }
public Heartbeat buildHeartbeat() {
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AutoSerializableInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS = Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_SERIALIZEUID_FIELD_NAME = "serialVersionUID"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_SERIALIZEUID_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_SERIALIZEUID_FIELD_VALUE = 0L;
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_VALUE; import java.io.Serializable; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Automatically transforms classes passed in such that they implement {@link Serializable} and assign a {@code serialVersionUID} of 0. // // This is vital for the serialization feature (if the user uses the default serializer). If your class doesn't extend {@link Serializable}, // you'll get an exception when serializing it. Also, if you don't hardcode a {@code serialVersionUID} onto the class, any change to the // class will cause deserialization to fail. These 2 properties are features of Java's built-in serialization mechanism (used by the default // serializer). final class AutoSerializableInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Should we skip this? if (!state.instrumentationSettings().isAutoSerializable()) { return; } // Skip if interface if ((classNode.access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE) { throw new IllegalArgumentException("Auto-serializing an interface not allowed"); } //Add the field in Type serializableType = Type.getType(Serializable.class); String serializableTypeStr = serializableType.getInternalName(); if (!classNode.interfaces.contains(serializableTypeStr)) { classNode.interfaces.add(serializableTypeStr); }
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS = Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_SERIALIZEUID_FIELD_NAME = "serialVersionUID"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_SERIALIZEUID_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_SERIALIZEUID_FIELD_VALUE = 0L; // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AutoSerializableInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_VALUE; import java.io.Serializable; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Automatically transforms classes passed in such that they implement {@link Serializable} and assign a {@code serialVersionUID} of 0. // // This is vital for the serialization feature (if the user uses the default serializer). If your class doesn't extend {@link Serializable}, // you'll get an exception when serializing it. Also, if you don't hardcode a {@code serialVersionUID} onto the class, any change to the // class will cause deserialization to fail. These 2 properties are features of Java's built-in serialization mechanism (used by the default // serializer). final class AutoSerializableInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Should we skip this? if (!state.instrumentationSettings().isAutoSerializable()) { return; } // Skip if interface if ((classNode.access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE) { throw new IllegalArgumentException("Auto-serializing an interface not allowed"); } //Add the field in Type serializableType = Type.getType(Serializable.class); String serializableTypeStr = serializableType.getInternalName(); if (!classNode.interfaces.contains(serializableTypeStr)) { classNode.interfaces.add(serializableTypeStr); }
if (!classNode.fields.stream().anyMatch(fn -> INSTRUMENTED_SERIALIZEUID_FIELD_NAME.equals(fn.name))) {
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AutoSerializableInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS = Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_SERIALIZEUID_FIELD_NAME = "serialVersionUID"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_SERIALIZEUID_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_SERIALIZEUID_FIELD_VALUE = 0L;
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_VALUE; import java.io.Serializable; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Automatically transforms classes passed in such that they implement {@link Serializable} and assign a {@code serialVersionUID} of 0. // // This is vital for the serialization feature (if the user uses the default serializer). If your class doesn't extend {@link Serializable}, // you'll get an exception when serializing it. Also, if you don't hardcode a {@code serialVersionUID} onto the class, any change to the // class will cause deserialization to fail. These 2 properties are features of Java's built-in serialization mechanism (used by the default // serializer). final class AutoSerializableInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Should we skip this? if (!state.instrumentationSettings().isAutoSerializable()) { return; } // Skip if interface if ((classNode.access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE) { throw new IllegalArgumentException("Auto-serializing an interface not allowed"); } //Add the field in Type serializableType = Type.getType(Serializable.class); String serializableTypeStr = serializableType.getInternalName(); if (!classNode.interfaces.contains(serializableTypeStr)) { classNode.interfaces.add(serializableTypeStr); } if (!classNode.fields.stream().anyMatch(fn -> INSTRUMENTED_SERIALIZEUID_FIELD_NAME.equals(fn.name))) { FieldNode serialVersionUIDFieldNode = new FieldNode(
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS = Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_SERIALIZEUID_FIELD_NAME = "serialVersionUID"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_SERIALIZEUID_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_SERIALIZEUID_FIELD_VALUE = 0L; // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AutoSerializableInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_VALUE; import java.io.Serializable; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Automatically transforms classes passed in such that they implement {@link Serializable} and assign a {@code serialVersionUID} of 0. // // This is vital for the serialization feature (if the user uses the default serializer). If your class doesn't extend {@link Serializable}, // you'll get an exception when serializing it. Also, if you don't hardcode a {@code serialVersionUID} onto the class, any change to the // class will cause deserialization to fail. These 2 properties are features of Java's built-in serialization mechanism (used by the default // serializer). final class AutoSerializableInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Should we skip this? if (!state.instrumentationSettings().isAutoSerializable()) { return; } // Skip if interface if ((classNode.access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE) { throw new IllegalArgumentException("Auto-serializing an interface not allowed"); } //Add the field in Type serializableType = Type.getType(Serializable.class); String serializableTypeStr = serializableType.getInternalName(); if (!classNode.interfaces.contains(serializableTypeStr)) { classNode.interfaces.add(serializableTypeStr); } if (!classNode.fields.stream().anyMatch(fn -> INSTRUMENTED_SERIALIZEUID_FIELD_NAME.equals(fn.name))) { FieldNode serialVersionUIDFieldNode = new FieldNode(
INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS,
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AutoSerializableInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS = Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_SERIALIZEUID_FIELD_NAME = "serialVersionUID"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_SERIALIZEUID_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_SERIALIZEUID_FIELD_VALUE = 0L;
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_VALUE; import java.io.Serializable; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Automatically transforms classes passed in such that they implement {@link Serializable} and assign a {@code serialVersionUID} of 0. // // This is vital for the serialization feature (if the user uses the default serializer). If your class doesn't extend {@link Serializable}, // you'll get an exception when serializing it. Also, if you don't hardcode a {@code serialVersionUID} onto the class, any change to the // class will cause deserialization to fail. These 2 properties are features of Java's built-in serialization mechanism (used by the default // serializer). final class AutoSerializableInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Should we skip this? if (!state.instrumentationSettings().isAutoSerializable()) { return; } // Skip if interface if ((classNode.access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE) { throw new IllegalArgumentException("Auto-serializing an interface not allowed"); } //Add the field in Type serializableType = Type.getType(Serializable.class); String serializableTypeStr = serializableType.getInternalName(); if (!classNode.interfaces.contains(serializableTypeStr)) { classNode.interfaces.add(serializableTypeStr); } if (!classNode.fields.stream().anyMatch(fn -> INSTRUMENTED_SERIALIZEUID_FIELD_NAME.equals(fn.name))) { FieldNode serialVersionUIDFieldNode = new FieldNode( INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS, INSTRUMENTED_SERIALIZEUID_FIELD_NAME,
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS = Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_SERIALIZEUID_FIELD_NAME = "serialVersionUID"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_SERIALIZEUID_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_SERIALIZEUID_FIELD_VALUE = 0L; // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AutoSerializableInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_VALUE; import java.io.Serializable; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Automatically transforms classes passed in such that they implement {@link Serializable} and assign a {@code serialVersionUID} of 0. // // This is vital for the serialization feature (if the user uses the default serializer). If your class doesn't extend {@link Serializable}, // you'll get an exception when serializing it. Also, if you don't hardcode a {@code serialVersionUID} onto the class, any change to the // class will cause deserialization to fail. These 2 properties are features of Java's built-in serialization mechanism (used by the default // serializer). final class AutoSerializableInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Should we skip this? if (!state.instrumentationSettings().isAutoSerializable()) { return; } // Skip if interface if ((classNode.access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE) { throw new IllegalArgumentException("Auto-serializing an interface not allowed"); } //Add the field in Type serializableType = Type.getType(Serializable.class); String serializableTypeStr = serializableType.getInternalName(); if (!classNode.interfaces.contains(serializableTypeStr)) { classNode.interfaces.add(serializableTypeStr); } if (!classNode.fields.stream().anyMatch(fn -> INSTRUMENTED_SERIALIZEUID_FIELD_NAME.equals(fn.name))) { FieldNode serialVersionUIDFieldNode = new FieldNode( INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS, INSTRUMENTED_SERIALIZEUID_FIELD_NAME,
INSTRUMENTED_SERIALIZEUID_FIELD_TYPE.getDescriptor(),
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AutoSerializableInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS = Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_SERIALIZEUID_FIELD_NAME = "serialVersionUID"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_SERIALIZEUID_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_SERIALIZEUID_FIELD_VALUE = 0L;
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_VALUE; import java.io.Serializable; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Automatically transforms classes passed in such that they implement {@link Serializable} and assign a {@code serialVersionUID} of 0. // // This is vital for the serialization feature (if the user uses the default serializer). If your class doesn't extend {@link Serializable}, // you'll get an exception when serializing it. Also, if you don't hardcode a {@code serialVersionUID} onto the class, any change to the // class will cause deserialization to fail. These 2 properties are features of Java's built-in serialization mechanism (used by the default // serializer). final class AutoSerializableInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Should we skip this? if (!state.instrumentationSettings().isAutoSerializable()) { return; } // Skip if interface if ((classNode.access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE) { throw new IllegalArgumentException("Auto-serializing an interface not allowed"); } //Add the field in Type serializableType = Type.getType(Serializable.class); String serializableTypeStr = serializableType.getInternalName(); if (!classNode.interfaces.contains(serializableTypeStr)) { classNode.interfaces.add(serializableTypeStr); } if (!classNode.fields.stream().anyMatch(fn -> INSTRUMENTED_SERIALIZEUID_FIELD_NAME.equals(fn.name))) { FieldNode serialVersionUIDFieldNode = new FieldNode( INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS, INSTRUMENTED_SERIALIZEUID_FIELD_NAME, INSTRUMENTED_SERIALIZEUID_FIELD_TYPE.getDescriptor(), null,
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS = Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_SERIALIZEUID_FIELD_NAME = "serialVersionUID"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_SERIALIZEUID_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_SERIALIZEUID_FIELD_VALUE = 0L; // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AutoSerializableInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_SERIALIZEUID_FIELD_VALUE; import java.io.Serializable; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Automatically transforms classes passed in such that they implement {@link Serializable} and assign a {@code serialVersionUID} of 0. // // This is vital for the serialization feature (if the user uses the default serializer). If your class doesn't extend {@link Serializable}, // you'll get an exception when serializing it. Also, if you don't hardcode a {@code serialVersionUID} onto the class, any change to the // class will cause deserialization to fail. These 2 properties are features of Java's built-in serialization mechanism (used by the default // serializer). final class AutoSerializableInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Should we skip this? if (!state.instrumentationSettings().isAutoSerializable()) { return; } // Skip if interface if ((classNode.access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE) { throw new IllegalArgumentException("Auto-serializing an interface not allowed"); } //Add the field in Type serializableType = Type.getType(Serializable.class); String serializableTypeStr = serializableType.getInternalName(); if (!classNode.interfaces.contains(serializableTypeStr)) { classNode.interfaces.add(serializableTypeStr); } if (!classNode.fields.stream().anyMatch(fn -> INSTRUMENTED_SERIALIZEUID_FIELD_NAME.equals(fn.name))) { FieldNode serialVersionUIDFieldNode = new FieldNode( INSTRUMENTED_SERIALIZEUID_FIELD_ACCESS, INSTRUMENTED_SERIALIZEUID_FIELD_NAME, INSTRUMENTED_SERIALIZEUID_FIELD_TYPE.getDescriptor(), null,
INSTRUMENTED_SERIALIZEUID_FIELD_VALUE);
offbynull/coroutines
user/src/main/java/com/offbynull/coroutines/user/SerializedState.java
// Path: user/src/main/java/com/offbynull/coroutines/user/SerializationUtils.java // static final class FrameUpdatePointKey { // // private final String className; // private final int methodId; // private final int continuationPointId; // // FrameUpdatePointKey(String className, int methodId, int continuationPointId) { // if (className == null) { // throw new NullPointerException(); // } // // this.className = className; // this.methodId = methodId; // this.continuationPointId = continuationPointId; // } // // public int hashCode() { // int hash = 7; // hash = 71 * hash + (this.className != null ? this.className.hashCode() : 0); // hash = 71 * hash + this.methodId; // hash = 71 * hash + this.continuationPointId; // return hash; // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final FrameUpdatePointKey other = (FrameUpdatePointKey) obj; // if (this.methodId != other.methodId) { // return false; // } // if (this.continuationPointId != other.continuationPointId) { // return false; // } // if ((this.className == null) ? (other.className != null) : !this.className.equals(other.className)) { // return false; // } // return true; // } // } // // Path: user/src/main/java/com/offbynull/coroutines/user/SerializationUtils.java // static final class FrameUpdatePointValue { // private final FrameModifier frameModifier; // // FrameUpdatePointValue(FrameModifier frameModifier) { // if (frameModifier == null) { // throw new NullPointerException(); // } // this.frameModifier = frameModifier; // } // }
import com.offbynull.coroutines.user.SerializationUtils.FrameUpdatePointKey; import com.offbynull.coroutines.user.SerializationUtils.FrameUpdatePointValue; import java.io.Serializable;
public static final class FrameUpdatePoint { private final String className; private final int methodId; private final int continuationPointId; private final FrameModifier frameModifier; /** * Constructs a {@link FrameUpdatePoint} object. * @param className class name for the continuation point * @param methodId method id (used to identify method) * @param continuationPointId continuation point ID * @param frameModifier logic to modify the frame's contents to the new version * @throws NullPointerException if any argument is {@code null} * @throws IllegalArgumentException if {@code continuationPointId < 0}, or if {@code oldMethodId == @code newMethodId} */ public FrameUpdatePoint(String className, int methodId, int continuationPointId, FrameModifier frameModifier) { if (frameModifier == null) { throw new NullPointerException(); } if (continuationPointId < 0) { throw new IllegalArgumentException("Negative continuation point"); } this.className = className; this.methodId = methodId; this.continuationPointId = continuationPointId; this.frameModifier = frameModifier; }
// Path: user/src/main/java/com/offbynull/coroutines/user/SerializationUtils.java // static final class FrameUpdatePointKey { // // private final String className; // private final int methodId; // private final int continuationPointId; // // FrameUpdatePointKey(String className, int methodId, int continuationPointId) { // if (className == null) { // throw new NullPointerException(); // } // // this.className = className; // this.methodId = methodId; // this.continuationPointId = continuationPointId; // } // // public int hashCode() { // int hash = 7; // hash = 71 * hash + (this.className != null ? this.className.hashCode() : 0); // hash = 71 * hash + this.methodId; // hash = 71 * hash + this.continuationPointId; // return hash; // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final FrameUpdatePointKey other = (FrameUpdatePointKey) obj; // if (this.methodId != other.methodId) { // return false; // } // if (this.continuationPointId != other.continuationPointId) { // return false; // } // if ((this.className == null) ? (other.className != null) : !this.className.equals(other.className)) { // return false; // } // return true; // } // } // // Path: user/src/main/java/com/offbynull/coroutines/user/SerializationUtils.java // static final class FrameUpdatePointValue { // private final FrameModifier frameModifier; // // FrameUpdatePointValue(FrameModifier frameModifier) { // if (frameModifier == null) { // throw new NullPointerException(); // } // this.frameModifier = frameModifier; // } // } // Path: user/src/main/java/com/offbynull/coroutines/user/SerializedState.java import com.offbynull.coroutines.user.SerializationUtils.FrameUpdatePointKey; import com.offbynull.coroutines.user.SerializationUtils.FrameUpdatePointValue; import java.io.Serializable; public static final class FrameUpdatePoint { private final String className; private final int methodId; private final int continuationPointId; private final FrameModifier frameModifier; /** * Constructs a {@link FrameUpdatePoint} object. * @param className class name for the continuation point * @param methodId method id (used to identify method) * @param continuationPointId continuation point ID * @param frameModifier logic to modify the frame's contents to the new version * @throws NullPointerException if any argument is {@code null} * @throws IllegalArgumentException if {@code continuationPointId < 0}, or if {@code oldMethodId == @code newMethodId} */ public FrameUpdatePoint(String className, int methodId, int continuationPointId, FrameModifier frameModifier) { if (frameModifier == null) { throw new NullPointerException(); } if (continuationPointId < 0) { throw new IllegalArgumentException("Negative continuation point"); } this.className = className; this.methodId = methodId; this.continuationPointId = continuationPointId; this.frameModifier = frameModifier; }
FrameUpdatePointKey toKey() {
offbynull/coroutines
user/src/main/java/com/offbynull/coroutines/user/SerializedState.java
// Path: user/src/main/java/com/offbynull/coroutines/user/SerializationUtils.java // static final class FrameUpdatePointKey { // // private final String className; // private final int methodId; // private final int continuationPointId; // // FrameUpdatePointKey(String className, int methodId, int continuationPointId) { // if (className == null) { // throw new NullPointerException(); // } // // this.className = className; // this.methodId = methodId; // this.continuationPointId = continuationPointId; // } // // public int hashCode() { // int hash = 7; // hash = 71 * hash + (this.className != null ? this.className.hashCode() : 0); // hash = 71 * hash + this.methodId; // hash = 71 * hash + this.continuationPointId; // return hash; // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final FrameUpdatePointKey other = (FrameUpdatePointKey) obj; // if (this.methodId != other.methodId) { // return false; // } // if (this.continuationPointId != other.continuationPointId) { // return false; // } // if ((this.className == null) ? (other.className != null) : !this.className.equals(other.className)) { // return false; // } // return true; // } // } // // Path: user/src/main/java/com/offbynull/coroutines/user/SerializationUtils.java // static final class FrameUpdatePointValue { // private final FrameModifier frameModifier; // // FrameUpdatePointValue(FrameModifier frameModifier) { // if (frameModifier == null) { // throw new NullPointerException(); // } // this.frameModifier = frameModifier; // } // }
import com.offbynull.coroutines.user.SerializationUtils.FrameUpdatePointKey; import com.offbynull.coroutines.user.SerializationUtils.FrameUpdatePointValue; import java.io.Serializable;
private final int continuationPointId; private final FrameModifier frameModifier; /** * Constructs a {@link FrameUpdatePoint} object. * @param className class name for the continuation point * @param methodId method id (used to identify method) * @param continuationPointId continuation point ID * @param frameModifier logic to modify the frame's contents to the new version * @throws NullPointerException if any argument is {@code null} * @throws IllegalArgumentException if {@code continuationPointId < 0}, or if {@code oldMethodId == @code newMethodId} */ public FrameUpdatePoint(String className, int methodId, int continuationPointId, FrameModifier frameModifier) { if (frameModifier == null) { throw new NullPointerException(); } if (continuationPointId < 0) { throw new IllegalArgumentException("Negative continuation point"); } this.className = className; this.methodId = methodId; this.continuationPointId = continuationPointId; this.frameModifier = frameModifier; } FrameUpdatePointKey toKey() { return new FrameUpdatePointKey(className, methodId, continuationPointId); }
// Path: user/src/main/java/com/offbynull/coroutines/user/SerializationUtils.java // static final class FrameUpdatePointKey { // // private final String className; // private final int methodId; // private final int continuationPointId; // // FrameUpdatePointKey(String className, int methodId, int continuationPointId) { // if (className == null) { // throw new NullPointerException(); // } // // this.className = className; // this.methodId = methodId; // this.continuationPointId = continuationPointId; // } // // public int hashCode() { // int hash = 7; // hash = 71 * hash + (this.className != null ? this.className.hashCode() : 0); // hash = 71 * hash + this.methodId; // hash = 71 * hash + this.continuationPointId; // return hash; // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final FrameUpdatePointKey other = (FrameUpdatePointKey) obj; // if (this.methodId != other.methodId) { // return false; // } // if (this.continuationPointId != other.continuationPointId) { // return false; // } // if ((this.className == null) ? (other.className != null) : !this.className.equals(other.className)) { // return false; // } // return true; // } // } // // Path: user/src/main/java/com/offbynull/coroutines/user/SerializationUtils.java // static final class FrameUpdatePointValue { // private final FrameModifier frameModifier; // // FrameUpdatePointValue(FrameModifier frameModifier) { // if (frameModifier == null) { // throw new NullPointerException(); // } // this.frameModifier = frameModifier; // } // } // Path: user/src/main/java/com/offbynull/coroutines/user/SerializedState.java import com.offbynull.coroutines.user.SerializationUtils.FrameUpdatePointKey; import com.offbynull.coroutines.user.SerializationUtils.FrameUpdatePointValue; import java.io.Serializable; private final int continuationPointId; private final FrameModifier frameModifier; /** * Constructs a {@link FrameUpdatePoint} object. * @param className class name for the continuation point * @param methodId method id (used to identify method) * @param continuationPointId continuation point ID * @param frameModifier logic to modify the frame's contents to the new version * @throws NullPointerException if any argument is {@code null} * @throws IllegalArgumentException if {@code continuationPointId < 0}, or if {@code oldMethodId == @code newMethodId} */ public FrameUpdatePoint(String className, int methodId, int continuationPointId, FrameModifier frameModifier) { if (frameModifier == null) { throw new NullPointerException(); } if (continuationPointId < 0) { throw new IllegalArgumentException("Negative continuation point"); } this.className = className; this.methodId = methodId; this.continuationPointId = continuationPointId; this.frameModifier = frameModifier; } FrameUpdatePointKey toKey() { return new FrameUpdatePointKey(className, methodId, continuationPointId); }
FrameUpdatePointValue toValue() {
offbynull/coroutines
instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/asm/SimpleClassNodeTest.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/SearchUtils.java // public static List<AbstractInsnNode> searchForOpcodes(InsnList insnList, int ... opcodes) { // Validate.notNull(insnList); // Validate.notNull(opcodes); // Validate.isTrue(opcodes.length > 0); // // List<AbstractInsnNode> ret = new LinkedList<>(); // // Set<Integer> opcodeSet = new HashSet<>(); // Arrays.stream(opcodes).forEach((x) -> opcodeSet.add(x)); // // Iterator<AbstractInsnNode> it = insnList.iterator(); // while (it.hasNext()) { // AbstractInsnNode insnNode = it.next(); // if (opcodeSet.contains(insnNode.getOpcode())) { // ret.add(insnNode); // } // } // // return ret; // } // // Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/testhelpers/TestUtils.java // public static Map<String, byte[]> readZipFromResource(String path) throws IOException { // ClassLoader cl = ClassLoader.getSystemClassLoader(); // URL url = cl.getResource(path); // Validate.isTrue(url != null); // // Map<String, byte[]> ret = new LinkedHashMap<>(); // // try (InputStream is = url.openStream(); // ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) { // ZipArchiveEntry entry; // while ((entry = zais.getNextZipEntry()) != null) { // ret.put(entry.getName(), IOUtils.toByteArray(zais)); // } // } // // return ret; // }
import static com.offbynull.coroutines.instrumenter.asm.SearchUtils.searchForOpcodes; import static com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.readZipFromResource; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode;
package com.offbynull.coroutines.instrumenter.asm; public class SimpleClassNodeTest { @Test public void mustNotFindAnyJsrInstructions() throws Exception {
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/SearchUtils.java // public static List<AbstractInsnNode> searchForOpcodes(InsnList insnList, int ... opcodes) { // Validate.notNull(insnList); // Validate.notNull(opcodes); // Validate.isTrue(opcodes.length > 0); // // List<AbstractInsnNode> ret = new LinkedList<>(); // // Set<Integer> opcodeSet = new HashSet<>(); // Arrays.stream(opcodes).forEach((x) -> opcodeSet.add(x)); // // Iterator<AbstractInsnNode> it = insnList.iterator(); // while (it.hasNext()) { // AbstractInsnNode insnNode = it.next(); // if (opcodeSet.contains(insnNode.getOpcode())) { // ret.add(insnNode); // } // } // // return ret; // } // // Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/testhelpers/TestUtils.java // public static Map<String, byte[]> readZipFromResource(String path) throws IOException { // ClassLoader cl = ClassLoader.getSystemClassLoader(); // URL url = cl.getResource(path); // Validate.isTrue(url != null); // // Map<String, byte[]> ret = new LinkedHashMap<>(); // // try (InputStream is = url.openStream(); // ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) { // ZipArchiveEntry entry; // while ((entry = zais.getNextZipEntry()) != null) { // ret.put(entry.getName(), IOUtils.toByteArray(zais)); // } // } // // return ret; // } // Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/asm/SimpleClassNodeTest.java import static com.offbynull.coroutines.instrumenter.asm.SearchUtils.searchForOpcodes; import static com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.readZipFromResource; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; package com.offbynull.coroutines.instrumenter.asm; public class SimpleClassNodeTest { @Test public void mustNotFindAnyJsrInstructions() throws Exception {
byte[] input = readZipFromResource("JsrExceptionSuspendTest.zip").get("JsrExceptionSuspendTest.class");
offbynull/coroutines
instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/asm/SimpleClassNodeTest.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/SearchUtils.java // public static List<AbstractInsnNode> searchForOpcodes(InsnList insnList, int ... opcodes) { // Validate.notNull(insnList); // Validate.notNull(opcodes); // Validate.isTrue(opcodes.length > 0); // // List<AbstractInsnNode> ret = new LinkedList<>(); // // Set<Integer> opcodeSet = new HashSet<>(); // Arrays.stream(opcodes).forEach((x) -> opcodeSet.add(x)); // // Iterator<AbstractInsnNode> it = insnList.iterator(); // while (it.hasNext()) { // AbstractInsnNode insnNode = it.next(); // if (opcodeSet.contains(insnNode.getOpcode())) { // ret.add(insnNode); // } // } // // return ret; // } // // Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/testhelpers/TestUtils.java // public static Map<String, byte[]> readZipFromResource(String path) throws IOException { // ClassLoader cl = ClassLoader.getSystemClassLoader(); // URL url = cl.getResource(path); // Validate.isTrue(url != null); // // Map<String, byte[]> ret = new LinkedHashMap<>(); // // try (InputStream is = url.openStream(); // ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) { // ZipArchiveEntry entry; // while ((entry = zais.getNextZipEntry()) != null) { // ret.put(entry.getName(), IOUtils.toByteArray(zais)); // } // } // // return ret; // }
import static com.offbynull.coroutines.instrumenter.asm.SearchUtils.searchForOpcodes; import static com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.readZipFromResource; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode;
package com.offbynull.coroutines.instrumenter.asm; public class SimpleClassNodeTest { @Test public void mustNotFindAnyJsrInstructions() throws Exception { byte[] input = readZipFromResource("JsrExceptionSuspendTest.zip").get("JsrExceptionSuspendTest.class"); ClassReader cr = new ClassReader(input); ClassNode classNode = new SimpleClassNode(); cr.accept(classNode, 0); for (MethodNode methodNode : classNode.methods) {
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/SearchUtils.java // public static List<AbstractInsnNode> searchForOpcodes(InsnList insnList, int ... opcodes) { // Validate.notNull(insnList); // Validate.notNull(opcodes); // Validate.isTrue(opcodes.length > 0); // // List<AbstractInsnNode> ret = new LinkedList<>(); // // Set<Integer> opcodeSet = new HashSet<>(); // Arrays.stream(opcodes).forEach((x) -> opcodeSet.add(x)); // // Iterator<AbstractInsnNode> it = insnList.iterator(); // while (it.hasNext()) { // AbstractInsnNode insnNode = it.next(); // if (opcodeSet.contains(insnNode.getOpcode())) { // ret.add(insnNode); // } // } // // return ret; // } // // Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/testhelpers/TestUtils.java // public static Map<String, byte[]> readZipFromResource(String path) throws IOException { // ClassLoader cl = ClassLoader.getSystemClassLoader(); // URL url = cl.getResource(path); // Validate.isTrue(url != null); // // Map<String, byte[]> ret = new LinkedHashMap<>(); // // try (InputStream is = url.openStream(); // ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) { // ZipArchiveEntry entry; // while ((entry = zais.getNextZipEntry()) != null) { // ret.put(entry.getName(), IOUtils.toByteArray(zais)); // } // } // // return ret; // } // Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/asm/SimpleClassNodeTest.java import static com.offbynull.coroutines.instrumenter.asm.SearchUtils.searchForOpcodes; import static com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.readZipFromResource; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; package com.offbynull.coroutines.instrumenter.asm; public class SimpleClassNodeTest { @Test public void mustNotFindAnyJsrInstructions() throws Exception { byte[] input = readZipFromResource("JsrExceptionSuspendTest.zip").get("JsrExceptionSuspendTest.class"); ClassReader cr = new ClassReader(input); ClassNode classNode = new SimpleClassNode(); cr.accept(classNode, 0); for (MethodNode methodNode : classNode.methods) {
assertTrue(searchForOpcodes(methodNode.instructions, Opcodes.JSR).isEmpty());
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationPostInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_METHODID_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_METHODID_FIELD_TYPE = Type.INT_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Integer INSTRUMENTED_METHODID_FIELD_VALUE = 0; // // Path: user/src/main/java/com/offbynull/coroutines/user/MethodState.java // public static String getIdentifyingFieldName(int methodId, int continuationPointId) { // if (continuationPointId < 0) { // throw new IllegalArgumentException(); // } // // String methodIdStr = Integer.toString(methodId).replace('-', 'N'); // String continuationPointIdStr = Integer.toString(continuationPointId).replace('-', 'N'); // return "__COROUTINES_ID_" + methodIdStr + "_" + continuationPointIdStr; // }
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_VALUE; import static com.offbynull.coroutines.user.MethodState.getIdentifyingFieldName; import org.objectweb.asm.tree.ClassNode; import java.util.Map; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Adds fields used by serializer/deserializer to identify which version of the method its working with. final class SerializationPostInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Generate the fields needed by the serializer/deserializer for (Map.Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodAttributes methodAttrs = method.getValue(); UnmodifiableList<ContinuationPoint> continuationPoints = methodAttrs.getContinuationPoints(); // Shove in versioning info for the method as a fields on the class. int methodId = methodAttrs.getSignature().getMethodId(); for (int i = 0; i < continuationPoints.size(); i++) { int continuationPointId = i; FieldNode methodIdField = new FieldNode(
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_METHODID_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_METHODID_FIELD_TYPE = Type.INT_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Integer INSTRUMENTED_METHODID_FIELD_VALUE = 0; // // Path: user/src/main/java/com/offbynull/coroutines/user/MethodState.java // public static String getIdentifyingFieldName(int methodId, int continuationPointId) { // if (continuationPointId < 0) { // throw new IllegalArgumentException(); // } // // String methodIdStr = Integer.toString(methodId).replace('-', 'N'); // String continuationPointIdStr = Integer.toString(continuationPointId).replace('-', 'N'); // return "__COROUTINES_ID_" + methodIdStr + "_" + continuationPointIdStr; // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationPostInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_VALUE; import static com.offbynull.coroutines.user.MethodState.getIdentifyingFieldName; import org.objectweb.asm.tree.ClassNode; import java.util.Map; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Adds fields used by serializer/deserializer to identify which version of the method its working with. final class SerializationPostInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Generate the fields needed by the serializer/deserializer for (Map.Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodAttributes methodAttrs = method.getValue(); UnmodifiableList<ContinuationPoint> continuationPoints = methodAttrs.getContinuationPoints(); // Shove in versioning info for the method as a fields on the class. int methodId = methodAttrs.getSignature().getMethodId(); for (int i = 0; i < continuationPoints.size(); i++) { int continuationPointId = i; FieldNode methodIdField = new FieldNode(
INSTRUMENTED_METHODID_FIELD_ACCESS,
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationPostInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_METHODID_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_METHODID_FIELD_TYPE = Type.INT_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Integer INSTRUMENTED_METHODID_FIELD_VALUE = 0; // // Path: user/src/main/java/com/offbynull/coroutines/user/MethodState.java // public static String getIdentifyingFieldName(int methodId, int continuationPointId) { // if (continuationPointId < 0) { // throw new IllegalArgumentException(); // } // // String methodIdStr = Integer.toString(methodId).replace('-', 'N'); // String continuationPointIdStr = Integer.toString(continuationPointId).replace('-', 'N'); // return "__COROUTINES_ID_" + methodIdStr + "_" + continuationPointIdStr; // }
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_VALUE; import static com.offbynull.coroutines.user.MethodState.getIdentifyingFieldName; import org.objectweb.asm.tree.ClassNode; import java.util.Map; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Adds fields used by serializer/deserializer to identify which version of the method its working with. final class SerializationPostInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Generate the fields needed by the serializer/deserializer for (Map.Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodAttributes methodAttrs = method.getValue(); UnmodifiableList<ContinuationPoint> continuationPoints = methodAttrs.getContinuationPoints(); // Shove in versioning info for the method as a fields on the class. int methodId = methodAttrs.getSignature().getMethodId(); for (int i = 0; i < continuationPoints.size(); i++) { int continuationPointId = i; FieldNode methodIdField = new FieldNode( INSTRUMENTED_METHODID_FIELD_ACCESS,
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_METHODID_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_METHODID_FIELD_TYPE = Type.INT_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Integer INSTRUMENTED_METHODID_FIELD_VALUE = 0; // // Path: user/src/main/java/com/offbynull/coroutines/user/MethodState.java // public static String getIdentifyingFieldName(int methodId, int continuationPointId) { // if (continuationPointId < 0) { // throw new IllegalArgumentException(); // } // // String methodIdStr = Integer.toString(methodId).replace('-', 'N'); // String continuationPointIdStr = Integer.toString(continuationPointId).replace('-', 'N'); // return "__COROUTINES_ID_" + methodIdStr + "_" + continuationPointIdStr; // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationPostInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_VALUE; import static com.offbynull.coroutines.user.MethodState.getIdentifyingFieldName; import org.objectweb.asm.tree.ClassNode; import java.util.Map; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Adds fields used by serializer/deserializer to identify which version of the method its working with. final class SerializationPostInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Generate the fields needed by the serializer/deserializer for (Map.Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodAttributes methodAttrs = method.getValue(); UnmodifiableList<ContinuationPoint> continuationPoints = methodAttrs.getContinuationPoints(); // Shove in versioning info for the method as a fields on the class. int methodId = methodAttrs.getSignature().getMethodId(); for (int i = 0; i < continuationPoints.size(); i++) { int continuationPointId = i; FieldNode methodIdField = new FieldNode( INSTRUMENTED_METHODID_FIELD_ACCESS,
getIdentifyingFieldName(methodId, continuationPointId),
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationPostInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_METHODID_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_METHODID_FIELD_TYPE = Type.INT_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Integer INSTRUMENTED_METHODID_FIELD_VALUE = 0; // // Path: user/src/main/java/com/offbynull/coroutines/user/MethodState.java // public static String getIdentifyingFieldName(int methodId, int continuationPointId) { // if (continuationPointId < 0) { // throw new IllegalArgumentException(); // } // // String methodIdStr = Integer.toString(methodId).replace('-', 'N'); // String continuationPointIdStr = Integer.toString(continuationPointId).replace('-', 'N'); // return "__COROUTINES_ID_" + methodIdStr + "_" + continuationPointIdStr; // }
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_VALUE; import static com.offbynull.coroutines.user.MethodState.getIdentifyingFieldName; import org.objectweb.asm.tree.ClassNode; import java.util.Map; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Adds fields used by serializer/deserializer to identify which version of the method its working with. final class SerializationPostInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Generate the fields needed by the serializer/deserializer for (Map.Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodAttributes methodAttrs = method.getValue(); UnmodifiableList<ContinuationPoint> continuationPoints = methodAttrs.getContinuationPoints(); // Shove in versioning info for the method as a fields on the class. int methodId = methodAttrs.getSignature().getMethodId(); for (int i = 0; i < continuationPoints.size(); i++) { int continuationPointId = i; FieldNode methodIdField = new FieldNode( INSTRUMENTED_METHODID_FIELD_ACCESS, getIdentifyingFieldName(methodId, continuationPointId),
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_METHODID_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_METHODID_FIELD_TYPE = Type.INT_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Integer INSTRUMENTED_METHODID_FIELD_VALUE = 0; // // Path: user/src/main/java/com/offbynull/coroutines/user/MethodState.java // public static String getIdentifyingFieldName(int methodId, int continuationPointId) { // if (continuationPointId < 0) { // throw new IllegalArgumentException(); // } // // String methodIdStr = Integer.toString(methodId).replace('-', 'N'); // String continuationPointIdStr = Integer.toString(continuationPointId).replace('-', 'N'); // return "__COROUTINES_ID_" + methodIdStr + "_" + continuationPointIdStr; // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationPostInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_VALUE; import static com.offbynull.coroutines.user.MethodState.getIdentifyingFieldName; import org.objectweb.asm.tree.ClassNode; import java.util.Map; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Adds fields used by serializer/deserializer to identify which version of the method its working with. final class SerializationPostInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Generate the fields needed by the serializer/deserializer for (Map.Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodAttributes methodAttrs = method.getValue(); UnmodifiableList<ContinuationPoint> continuationPoints = methodAttrs.getContinuationPoints(); // Shove in versioning info for the method as a fields on the class. int methodId = methodAttrs.getSignature().getMethodId(); for (int i = 0; i < continuationPoints.size(); i++) { int continuationPointId = i; FieldNode methodIdField = new FieldNode( INSTRUMENTED_METHODID_FIELD_ACCESS, getIdentifyingFieldName(methodId, continuationPointId),
INSTRUMENTED_METHODID_FIELD_TYPE.getDescriptor(),
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationPostInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_METHODID_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_METHODID_FIELD_TYPE = Type.INT_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Integer INSTRUMENTED_METHODID_FIELD_VALUE = 0; // // Path: user/src/main/java/com/offbynull/coroutines/user/MethodState.java // public static String getIdentifyingFieldName(int methodId, int continuationPointId) { // if (continuationPointId < 0) { // throw new IllegalArgumentException(); // } // // String methodIdStr = Integer.toString(methodId).replace('-', 'N'); // String continuationPointIdStr = Integer.toString(continuationPointId).replace('-', 'N'); // return "__COROUTINES_ID_" + methodIdStr + "_" + continuationPointIdStr; // }
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_VALUE; import static com.offbynull.coroutines.user.MethodState.getIdentifyingFieldName; import org.objectweb.asm.tree.ClassNode; import java.util.Map; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Adds fields used by serializer/deserializer to identify which version of the method its working with. final class SerializationPostInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Generate the fields needed by the serializer/deserializer for (Map.Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodAttributes methodAttrs = method.getValue(); UnmodifiableList<ContinuationPoint> continuationPoints = methodAttrs.getContinuationPoints(); // Shove in versioning info for the method as a fields on the class. int methodId = methodAttrs.getSignature().getMethodId(); for (int i = 0; i < continuationPoints.size(); i++) { int continuationPointId = i; FieldNode methodIdField = new FieldNode( INSTRUMENTED_METHODID_FIELD_ACCESS, getIdentifyingFieldName(methodId, continuationPointId), INSTRUMENTED_METHODID_FIELD_TYPE.getDescriptor(), null,
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_METHODID_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_METHODID_FIELD_TYPE = Type.INT_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Integer INSTRUMENTED_METHODID_FIELD_VALUE = 0; // // Path: user/src/main/java/com/offbynull/coroutines/user/MethodState.java // public static String getIdentifyingFieldName(int methodId, int continuationPointId) { // if (continuationPointId < 0) { // throw new IllegalArgumentException(); // } // // String methodIdStr = Integer.toString(methodId).replace('-', 'N'); // String continuationPointIdStr = Integer.toString(continuationPointId).replace('-', 'N'); // return "__COROUTINES_ID_" + methodIdStr + "_" + continuationPointIdStr; // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationPostInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_METHODID_FIELD_VALUE; import static com.offbynull.coroutines.user.MethodState.getIdentifyingFieldName; import org.objectweb.asm.tree.ClassNode; import java.util.Map; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Adds fields used by serializer/deserializer to identify which version of the method its working with. final class SerializationPostInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Generate the fields needed by the serializer/deserializer for (Map.Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodAttributes methodAttrs = method.getValue(); UnmodifiableList<ContinuationPoint> continuationPoints = methodAttrs.getContinuationPoints(); // Shove in versioning info for the method as a fields on the class. int methodId = methodAttrs.getSignature().getMethodId(); for (int i = 0; i < continuationPoints.size(); i++) { int continuationPointId = i; FieldNode methodIdField = new FieldNode( INSTRUMENTED_METHODID_FIELD_ACCESS, getIdentifyingFieldName(methodId, continuationPointId), INSTRUMENTED_METHODID_FIELD_TYPE.getDescriptor(), null,
INSTRUMENTED_METHODID_FIELD_VALUE);
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/PerformInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_MARKER_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_MARKER_FIELD_NAME = "__COROUTINES_INSTRUMENTATION_VERSION"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_MARKER_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_MARKER_FIELD_VALUE;
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_VALUE; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import java.util.Map.Entry; import org.apache.commons.lang3.Validate;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Main insturmentation pass. This is the instrumenter that re-works your logic such that your coroutines work. final class PerformInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Instrument the methods based on the analysis we did in previous passes MethodInstrumenter instrumenter = new MethodInstrumenter(); for (Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodNode methodNode = method.getKey(); MethodAttributes methodAttrs = method.getValue(); // Instrument instrumenter.instrument(classNode, methodNode, methodAttrs); } // Add the "Instrumented" marker field to this class so if we ever come back to it, we can skip it FieldNode instrumentedMarkerField = new FieldNode(
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_MARKER_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_MARKER_FIELD_NAME = "__COROUTINES_INSTRUMENTATION_VERSION"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_MARKER_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_MARKER_FIELD_VALUE; // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/PerformInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_VALUE; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import java.util.Map.Entry; import org.apache.commons.lang3.Validate; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Main insturmentation pass. This is the instrumenter that re-works your logic such that your coroutines work. final class PerformInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Instrument the methods based on the analysis we did in previous passes MethodInstrumenter instrumenter = new MethodInstrumenter(); for (Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodNode methodNode = method.getKey(); MethodAttributes methodAttrs = method.getValue(); // Instrument instrumenter.instrument(classNode, methodNode, methodAttrs); } // Add the "Instrumented" marker field to this class so if we ever come back to it, we can skip it FieldNode instrumentedMarkerField = new FieldNode(
INSTRUMENTED_MARKER_FIELD_ACCESS,
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/PerformInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_MARKER_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_MARKER_FIELD_NAME = "__COROUTINES_INSTRUMENTATION_VERSION"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_MARKER_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_MARKER_FIELD_VALUE;
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_VALUE; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import java.util.Map.Entry; import org.apache.commons.lang3.Validate;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Main insturmentation pass. This is the instrumenter that re-works your logic such that your coroutines work. final class PerformInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Instrument the methods based on the analysis we did in previous passes MethodInstrumenter instrumenter = new MethodInstrumenter(); for (Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodNode methodNode = method.getKey(); MethodAttributes methodAttrs = method.getValue(); // Instrument instrumenter.instrument(classNode, methodNode, methodAttrs); } // Add the "Instrumented" marker field to this class so if we ever come back to it, we can skip it FieldNode instrumentedMarkerField = new FieldNode( INSTRUMENTED_MARKER_FIELD_ACCESS,
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_MARKER_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_MARKER_FIELD_NAME = "__COROUTINES_INSTRUMENTATION_VERSION"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_MARKER_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_MARKER_FIELD_VALUE; // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/PerformInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_VALUE; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import java.util.Map.Entry; import org.apache.commons.lang3.Validate; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Main insturmentation pass. This is the instrumenter that re-works your logic such that your coroutines work. final class PerformInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Instrument the methods based on the analysis we did in previous passes MethodInstrumenter instrumenter = new MethodInstrumenter(); for (Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodNode methodNode = method.getKey(); MethodAttributes methodAttrs = method.getValue(); // Instrument instrumenter.instrument(classNode, methodNode, methodAttrs); } // Add the "Instrumented" marker field to this class so if we ever come back to it, we can skip it FieldNode instrumentedMarkerField = new FieldNode( INSTRUMENTED_MARKER_FIELD_ACCESS,
INSTRUMENTED_MARKER_FIELD_NAME,
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/PerformInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_MARKER_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_MARKER_FIELD_NAME = "__COROUTINES_INSTRUMENTATION_VERSION"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_MARKER_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_MARKER_FIELD_VALUE;
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_VALUE; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import java.util.Map.Entry; import org.apache.commons.lang3.Validate;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Main insturmentation pass. This is the instrumenter that re-works your logic such that your coroutines work. final class PerformInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Instrument the methods based on the analysis we did in previous passes MethodInstrumenter instrumenter = new MethodInstrumenter(); for (Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodNode methodNode = method.getKey(); MethodAttributes methodAttrs = method.getValue(); // Instrument instrumenter.instrument(classNode, methodNode, methodAttrs); } // Add the "Instrumented" marker field to this class so if we ever come back to it, we can skip it FieldNode instrumentedMarkerField = new FieldNode( INSTRUMENTED_MARKER_FIELD_ACCESS, INSTRUMENTED_MARKER_FIELD_NAME,
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_MARKER_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_MARKER_FIELD_NAME = "__COROUTINES_INSTRUMENTATION_VERSION"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_MARKER_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_MARKER_FIELD_VALUE; // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/PerformInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_VALUE; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import java.util.Map.Entry; import org.apache.commons.lang3.Validate; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Main insturmentation pass. This is the instrumenter that re-works your logic such that your coroutines work. final class PerformInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Instrument the methods based on the analysis we did in previous passes MethodInstrumenter instrumenter = new MethodInstrumenter(); for (Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodNode methodNode = method.getKey(); MethodAttributes methodAttrs = method.getValue(); // Instrument instrumenter.instrument(classNode, methodNode, methodAttrs); } // Add the "Instrumented" marker field to this class so if we ever come back to it, we can skip it FieldNode instrumentedMarkerField = new FieldNode( INSTRUMENTED_MARKER_FIELD_ACCESS, INSTRUMENTED_MARKER_FIELD_NAME,
INSTRUMENTED_MARKER_FIELD_TYPE.getDescriptor(),
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/PerformInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_MARKER_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_MARKER_FIELD_NAME = "__COROUTINES_INSTRUMENTATION_VERSION"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_MARKER_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_MARKER_FIELD_VALUE;
import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_VALUE; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import java.util.Map.Entry; import org.apache.commons.lang3.Validate;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Main insturmentation pass. This is the instrumenter that re-works your logic such that your coroutines work. final class PerformInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Instrument the methods based on the analysis we did in previous passes MethodInstrumenter instrumenter = new MethodInstrumenter(); for (Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodNode methodNode = method.getKey(); MethodAttributes methodAttrs = method.getValue(); // Instrument instrumenter.instrument(classNode, methodNode, methodAttrs); } // Add the "Instrumented" marker field to this class so if we ever come back to it, we can skip it FieldNode instrumentedMarkerField = new FieldNode( INSTRUMENTED_MARKER_FIELD_ACCESS, INSTRUMENTED_MARKER_FIELD_NAME, INSTRUMENTED_MARKER_FIELD_TYPE.getDescriptor(), null,
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final int INSTRUMENTED_MARKER_FIELD_ACCESS = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final String INSTRUMENTED_MARKER_FIELD_NAME = "__COROUTINES_INSTRUMENTATION_VERSION"; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Type INSTRUMENTED_MARKER_FIELD_TYPE = Type.LONG_TYPE; // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InternalFields.java // static final Long INSTRUMENTED_MARKER_FIELD_VALUE; // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/PerformInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_ACCESS; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_NAME; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_TYPE; import static com.offbynull.coroutines.instrumenter.InternalFields.INSTRUMENTED_MARKER_FIELD_VALUE; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import java.util.Map.Entry; import org.apache.commons.lang3.Validate; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Main insturmentation pass. This is the instrumenter that re-works your logic such that your coroutines work. final class PerformInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods attributes should be assigned at this point. Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x != null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Instrument the methods based on the analysis we did in previous passes MethodInstrumenter instrumenter = new MethodInstrumenter(); for (Entry<MethodNode, MethodAttributes> method : state.methodAttributes().entrySet()) { MethodNode methodNode = method.getKey(); MethodAttributes methodAttrs = method.getValue(); // Instrument instrumenter.instrument(classNode, methodNode, methodAttrs); } // Add the "Instrumented" marker field to this class so if we ever come back to it, we can skip it FieldNode instrumentedMarkerField = new FieldNode( INSTRUMENTED_MARKER_FIELD_ACCESS, INSTRUMENTED_MARKER_FIELD_NAME, INSTRUMENTED_MARKER_FIELD_TYPE.getDescriptor(), null,
INSTRUMENTED_MARKER_FIELD_VALUE);
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AnalyzeInstrumentationPass.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/ClassInformationRepository.java // public interface ClassInformationRepository { // // /** // * Get information for a class. // * <p> // * This method returns class information as if it were encountered in a class file. In a class file, if the class is an interface, then // * its superclass is set to {@link Object}. Note that this is different from what {@link Class#getSuperclass() } returns when the class // * represents an interface (it returns {@code null}). // * @param internalClassName internal class name // * @throws NullPointerException if any argument is {@code null} // * @return information for that class, or {@code null} if not found // */ // ClassInformation getInformation(String internalClassName); // // }
import static com.offbynull.coroutines.instrumenter.InstrumentationState.ControlFlag.NO_INSTRUMENT; import com.offbynull.coroutines.instrumenter.asm.ClassInformationRepository; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.Validate;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Analyze what has been marked for instrumentation (more methods may be filtered out here). final class AnalyzeInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods to instrument should be identified, but no method attributes should be assigned yet -- this is what this pass does. There // must be atleast 1 method to exist (previous pass should have stopped the instrumentation process if not) Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x == null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Analyze each method that needs to be instrumented
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/ClassInformationRepository.java // public interface ClassInformationRepository { // // /** // * Get information for a class. // * <p> // * This method returns class information as if it were encountered in a class file. In a class file, if the class is an interface, then // * its superclass is set to {@link Object}. Note that this is different from what {@link Class#getSuperclass() } returns when the class // * represents an interface (it returns {@code null}). // * @param internalClassName internal class name // * @throws NullPointerException if any argument is {@code null} // * @return information for that class, or {@code null} if not found // */ // ClassInformation getInformation(String internalClassName); // // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/AnalyzeInstrumentationPass.java import static com.offbynull.coroutines.instrumenter.InstrumentationState.ControlFlag.NO_INSTRUMENT; import com.offbynull.coroutines.instrumenter.asm.ClassInformationRepository; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.Validate; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; // Analyze what has been marked for instrumentation (more methods may be filtered out here). final class AnalyzeInstrumentationPass implements InstrumentationPass { @Override public void pass(ClassNode classNode, InstrumentationState state) { Validate.notNull(classNode); Validate.notNull(state); // Methods to instrument should be identified, but no method attributes should be assigned yet -- this is what this pass does. There // must be atleast 1 method to exist (previous pass should have stopped the instrumentation process if not) Validate.validState(!state.methodAttributes().isEmpty()); Validate.validState(state.methodAttributes().keySet().stream().allMatch(x -> x != null)); Validate.validState(state.methodAttributes().values().stream().allMatch(x -> x == null)); // Sanity check to make sure that we're only dealing with methodnodes in the classnode -- this should never trigger unless previous // passes mess up Validate.validState(classNode.methods.containsAll(state.methodAttributes().keySet())); // Analyze each method that needs to be instrumented
ClassInformationRepository classRepo = state.classInformationRepository();
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/LockVariables.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // } // // Path: user/src/main/java/com/offbynull/coroutines/user/LockState.java // public final class LockState implements Serializable { // private static final long serialVersionUID = 6L; // // // We use a linkedlist to make sure that we retain the order of monitors as they come in. Otherwise we're going to deal with deadlock // // issues if we have code structured with double locks. For example, imagine the following scenario... // // // // Method 1: // // synchronized(a) { // // synchronized(b) { // // continuation.suspend(); // // } // // } // // // // Method 2 (same as method1): // // synchronized(a) { // // synchronized(b) { // // continuation.suspend(); // // } // // } // // // // // // If we weren't ordered, we may end up coming back after a suspend and re-locking the monitors in the wrong order. For example, // // we may lock b before we lock a. That has the potential for a deadlock because another thread could execute the locking logic // // correctly (first a and then b). Dual locking without retaining the same order = a deadlock waiting to happen. // // // // Long story short: it's vital that we keep the order which locks happen // private LinkedList monitors = new LinkedList(); // // /** // * Do not use -- for internal use only. // * <p> // * Should be called after a MONITORENTER instruction has been executed. Tracks the object that MONITORENTER was used on. // * @param monitor object the MONITORENTER instruction was used on // */ // public void enter(Object monitor) { // if (monitor == null) { // throw new NullPointerException(); // } // // monitors.add(monitor); // } // // /** // * Do not use -- for internal use only. // * <p> // * Should be called after a MONITOREXIT instruction has been executed. Untracks the object that MONITOREXIT was used on. // * @param monitor object the MONITOREXIT instruction was used on // */ // public void exit(Object monitor) { // if (monitor == null) { // throw new NullPointerException(); // } // // // remove last // ListIterator it = monitors.listIterator(monitors.size()); // while (it.hasPrevious()) { // Object prev = it.previous(); // if (monitor == prev) { // Never use equals() to test equality. We always need to make sure that the objects are the same, we // // don't care if they're the objects are logically equivalent // it.remove(); // return; // } // } // // throw new IllegalArgumentException(); // not found // } // // /** // * Dumps monitors out as an array. Order is retained. // * @return monitors // */ // public Object[] toArray() { // return monitors.toArray(); // } // }
import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import com.offbynull.coroutines.user.LockState; import org.apache.commons.lang3.Validate; import org.objectweb.asm.Type;
/* * Copyright (c) 2016, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; final class LockVariables { private final Variable lockStateVar; private final Variable counterVar; private final Variable arrayLenVar; LockVariables( Variable lockStateVar, Variable counterVar, Variable arrayLenVar) { // vars can be null -- they'll be null if the analyzer determined tehy aren't required
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // } // // Path: user/src/main/java/com/offbynull/coroutines/user/LockState.java // public final class LockState implements Serializable { // private static final long serialVersionUID = 6L; // // // We use a linkedlist to make sure that we retain the order of monitors as they come in. Otherwise we're going to deal with deadlock // // issues if we have code structured with double locks. For example, imagine the following scenario... // // // // Method 1: // // synchronized(a) { // // synchronized(b) { // // continuation.suspend(); // // } // // } // // // // Method 2 (same as method1): // // synchronized(a) { // // synchronized(b) { // // continuation.suspend(); // // } // // } // // // // // // If we weren't ordered, we may end up coming back after a suspend and re-locking the monitors in the wrong order. For example, // // we may lock b before we lock a. That has the potential for a deadlock because another thread could execute the locking logic // // correctly (first a and then b). Dual locking without retaining the same order = a deadlock waiting to happen. // // // // Long story short: it's vital that we keep the order which locks happen // private LinkedList monitors = new LinkedList(); // // /** // * Do not use -- for internal use only. // * <p> // * Should be called after a MONITORENTER instruction has been executed. Tracks the object that MONITORENTER was used on. // * @param monitor object the MONITORENTER instruction was used on // */ // public void enter(Object monitor) { // if (monitor == null) { // throw new NullPointerException(); // } // // monitors.add(monitor); // } // // /** // * Do not use -- for internal use only. // * <p> // * Should be called after a MONITOREXIT instruction has been executed. Untracks the object that MONITOREXIT was used on. // * @param monitor object the MONITOREXIT instruction was used on // */ // public void exit(Object monitor) { // if (monitor == null) { // throw new NullPointerException(); // } // // // remove last // ListIterator it = monitors.listIterator(monitors.size()); // while (it.hasPrevious()) { // Object prev = it.previous(); // if (monitor == prev) { // Never use equals() to test equality. We always need to make sure that the objects are the same, we // // don't care if they're the objects are logically equivalent // it.remove(); // return; // } // } // // throw new IllegalArgumentException(); // not found // } // // /** // * Dumps monitors out as an array. Order is retained. // * @return monitors // */ // public Object[] toArray() { // return monitors.toArray(); // } // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/LockVariables.java import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import com.offbynull.coroutines.user.LockState; import org.apache.commons.lang3.Validate; import org.objectweb.asm.Type; /* * Copyright (c) 2016, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; final class LockVariables { private final Variable lockStateVar; private final Variable counterVar; private final Variable arrayLenVar; LockVariables( Variable lockStateVar, Variable counterVar, Variable arrayLenVar) { // vars can be null -- they'll be null if the analyzer determined tehy aren't required
Validate.isTrue(lockStateVar == null || lockStateVar.getType().equals(Type.getType(LockState.class)));
offbynull/coroutines
instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/asm/VariableTableTest.java
// Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/testhelpers/TestUtils.java // public static Map<String, byte[]> readZipFromResource(String path) throws IOException { // ClassLoader cl = ClassLoader.getSystemClassLoader(); // URL url = cl.getResource(path); // Validate.isTrue(url != null); // // Map<String, byte[]> ret = new LinkedHashMap<>(); // // try (InputStream is = url.openStream(); // ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) { // ZipArchiveEntry entry; // while ((entry = zais.getNextZipEntry()) != null) { // ret.put(entry.getName(), IOUtils.toByteArray(zais)); // } // } // // return ret; // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // }
import static com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.readZipFromResource; import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode;
package com.offbynull.coroutines.instrumenter.asm; public final class VariableTableTest { private ClassNode classNode; private MethodNode methodNode; @BeforeEach public void setUp() throws IOException {
// Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/testhelpers/TestUtils.java // public static Map<String, byte[]> readZipFromResource(String path) throws IOException { // ClassLoader cl = ClassLoader.getSystemClassLoader(); // URL url = cl.getResource(path); // Validate.isTrue(url != null); // // Map<String, byte[]> ret = new LinkedHashMap<>(); // // try (InputStream is = url.openStream(); // ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) { // ZipArchiveEntry entry; // while ((entry = zais.getNextZipEntry()) != null) { // ret.put(entry.getName(), IOUtils.toByteArray(zais)); // } // } // // return ret; // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // } // Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/asm/VariableTableTest.java import static com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.readZipFromResource; import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; package com.offbynull.coroutines.instrumenter.asm; public final class VariableTableTest { private ClassNode classNode; private MethodNode methodNode; @BeforeEach public void setUp() throws IOException {
byte[] classData = readZipFromResource("SimpleStub.zip").get("SimpleStub.class");
offbynull/coroutines
instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/asm/VariableTableTest.java
// Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/testhelpers/TestUtils.java // public static Map<String, byte[]> readZipFromResource(String path) throws IOException { // ClassLoader cl = ClassLoader.getSystemClassLoader(); // URL url = cl.getResource(path); // Validate.isTrue(url != null); // // Map<String, byte[]> ret = new LinkedHashMap<>(); // // try (InputStream is = url.openStream(); // ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) { // ZipArchiveEntry entry; // while ((entry = zais.getNextZipEntry()) != null) { // ret.put(entry.getName(), IOUtils.toByteArray(zais)); // } // } // // return ret; // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // }
import static com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.readZipFromResource; import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode;
package com.offbynull.coroutines.instrumenter.asm; public final class VariableTableTest { private ClassNode classNode; private MethodNode methodNode; @BeforeEach public void setUp() throws IOException { byte[] classData = readZipFromResource("SimpleStub.zip").get("SimpleStub.class"); ClassReader classReader = new ClassReader(classData); classNode = new ClassNode(); classReader.accept(classNode, 0); methodNode = classNode.methods.get(1); // stub should be here } @Test public void mustBeAbleToAccessThisReference() { VariableTable fixture = new VariableTable(classNode, methodNode);
// Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/testhelpers/TestUtils.java // public static Map<String, byte[]> readZipFromResource(String path) throws IOException { // ClassLoader cl = ClassLoader.getSystemClassLoader(); // URL url = cl.getResource(path); // Validate.isTrue(url != null); // // Map<String, byte[]> ret = new LinkedHashMap<>(); // // try (InputStream is = url.openStream(); // ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) { // ZipArchiveEntry entry; // while ((entry = zais.getNextZipEntry()) != null) { // ret.put(entry.getName(), IOUtils.toByteArray(zais)); // } // } // // return ret; // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // } // Path: instrumenter/src/test/java/com/offbynull/coroutines/instrumenter/asm/VariableTableTest.java import static com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.readZipFromResource; import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; package com.offbynull.coroutines.instrumenter.asm; public final class VariableTableTest { private ClassNode classNode; private MethodNode methodNode; @BeforeEach public void setUp() throws IOException { byte[] classData = readZipFromResource("SimpleStub.zip").get("SimpleStub.class"); ClassReader classReader = new ClassReader(classData); classNode = new ClassNode(); classReader.accept(classNode, 0); methodNode = classNode.methods.get(1); // stub should be here } @Test public void mustBeAbleToAccessThisReference() { VariableTable fixture = new VariableTable(classNode, methodNode);
Variable var = fixture.getArgument(0);
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InstrumentationState.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/ClassInformationRepository.java // public interface ClassInformationRepository { // // /** // * Get information for a class. // * <p> // * This method returns class information as if it were encountered in a class file. In a class file, if the class is an interface, then // * its superclass is set to {@link Object}. Note that this is different from what {@link Class#getSuperclass() } returns when the class // * represents an interface (it returns {@code null}). // * @param internalClassName internal class name // * @throws NullPointerException if any argument is {@code null} // * @return information for that class, or {@code null} if not found // */ // ClassInformation getInformation(String internalClassName); // // }
import com.offbynull.coroutines.instrumenter.asm.ClassInformationRepository; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.MethodNode;
/* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; final class InstrumentationState { private final InstrumentationSettings instrumentationSettings;
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/ClassInformationRepository.java // public interface ClassInformationRepository { // // /** // * Get information for a class. // * <p> // * This method returns class information as if it were encountered in a class file. In a class file, if the class is an interface, then // * its superclass is set to {@link Object}. Note that this is different from what {@link Class#getSuperclass() } returns when the class // * represents an interface (it returns {@code null}). // * @param internalClassName internal class name // * @throws NullPointerException if any argument is {@code null} // * @return information for that class, or {@code null} if not found // */ // ClassInformation getInformation(String internalClassName); // // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/InstrumentationState.java import com.offbynull.coroutines.instrumenter.asm.ClassInformationRepository; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.Validate; import org.objectweb.asm.tree.MethodNode; /* * Copyright (c) 2017, Kasra Faghihi, All rights reserved. * * This library 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 3.0 of the License, or (at your option) any later version. * * This library 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 library. */ package com.offbynull.coroutines.instrumenter; final class InstrumentationState { private final InstrumentationSettings instrumentationSettings;
private final ClassInformationRepository classInformationRepository;
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationDetailer.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/SearchUtils.java // public static LocalVariableNode findLocalVariableNodeForInstruction(List<LocalVariableNode> lvnList, InsnList insnList, // final AbstractInsnNode insnNode, int idx) { // Validate.notNull(insnList); // Validate.notNull(insnNode); // Validate.isTrue(idx >= 0); // // int insnIdx = insnList.indexOf(insnNode); // Validate.isTrue(insnIdx != -1); // // lvnList = lvnList.stream() // .filter(lvn -> lvn.index == idx) // filter to lvns at the index we want // .filter(lvn -> { // filter to lvns that's scope starts before the instruction we want // AbstractInsnNode currentInsnNode = insnNode.getPrevious(); // while (currentInsnNode != null) { // if (currentInsnNode == lvn.start) { // return true; // } // currentInsnNode = currentInsnNode.getPrevious(); // } // return false; // }) // .filter(lvn -> { // filter to lvns that's scope stops after the instruction we want // AbstractInsnNode currentInsnNode = insnNode.getNext(); // while (currentInsnNode != null) { // if (currentInsnNode == lvn.end) { // return true; // } // currentInsnNode = currentInsnNode.getNext(); // } // return false; // }) // .collect(Collectors.toList()); // // // // If we don't have any LVNs at this point, return null // if (lvnList.isEmpty()) { // return null; // } // // // // Should this be a list or should it always be a single entry? The problem is that there's nothing stopping multiple LVN's coming // // back for some instruction+lvt_index combination. // // // // The one thing we can be sure of at this point is that IF WE GET BACK MULTIPLE LVNs, THEY MUST OVERLAP AT SOME POINT. // // // The assumption at this point is... // // 1. LVNs are scoped such that the index of start label is BEFORE the index of the end label // // 2. LVNs must fully overlap, meaning that they can't go past each other's boundaries // // 3. LVNs can end at the same label, but they can't start at the same label // // e.g. not allowed // // x-----------x // // x--------x // // e.g. allowed // // x-----------x // // x--------x // // e.g. allowed // // x--------x // // x-----------x // // e.g. not allowed // // x--------x // // x-----------x // // // // Error out if you spot this -- someone will eventually report it and it'll get fixed // // // the following blocks of code are far from efficient, but they're easily readable/understandable // for (LocalVariableNode lvn : lvnList) { // test condition 1 // int start = insnList.indexOf(lvn.start); // int end = insnList.indexOf(lvn.end); // Validate.validState(end > start); // } // // for (LocalVariableNode lvnTester : lvnList) { // test condition 2 and 3 // int startTester = insnList.indexOf(lvnTester.start); // int endTester = insnList.indexOf(lvnTester.end); // Range rangeTester = Range.between(startTester, endTester); // // for (LocalVariableNode lvnTestee : lvnList) { // if (lvnTester == lvnTestee) { // continue; // } // // int startTestee = insnList.indexOf(lvnTestee.start); // int endTestee = insnList.indexOf(lvnTestee.end); // Range rangeTestee = Range.between(startTestee, endTestee); // // Range intersectRange = rangeTester.intersectionWith(rangeTestee); // Validate.validState(intersectRange.equals(rangeTester) || intersectRange.equals(rangeTestee)); // test condition 2 // // Validate.validState(rangeTester.getMinimum() != rangeTestee.getMinimum()); // test condition 3 // } // } // // // // Given that all the above assumptions are correct, the LVN with the smallest range will be the correct one. It's the one that's // // most tightly scoped around the instruction. // // e.g. // // x------------i----x // // x--------i-x // // x---i-x // // return Collections.min(lvnList, (o1, o2) -> { // int o1Len = insnList.indexOf(o1.end) - insnList.indexOf(o1.start); // int o2Len = insnList.indexOf(o2.end) - insnList.indexOf(o2.start); // return Integer.compare(o1Len, o2Len); // }); // }
import static com.offbynull.coroutines.instrumenter.asm.SearchUtils.findLocalVariableNodeForInstruction; import java.util.Locale; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.Type; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.BasicValue;
// container[4] has local variables that are Objects // container[5] has operands that are bytes/shorts/ints // container[6] has operands that are floats // container[7] has operands that are longs // container[8] has operands that are doubles // container[9] has operands that are Objects detailLocals(cp, methodNode, output); detailOperands(cp, output); output.append('\n'); } output.append('\n'); } private void detailLocals(ContinuationPoint cp, MethodNode methodNode, StringBuilder output) { int intIdx = 0; int floatIdx = 0; int doubleIdx = 0; int longIdx = 0; int objectIdx = 0; for (int j = 0; j < cp.getFrame().getLocals(); j++) { BasicValue local = cp.getFrame().getLocal(j); if (local.getType() == null) { // unused in frame, so skip over it continue; }
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/SearchUtils.java // public static LocalVariableNode findLocalVariableNodeForInstruction(List<LocalVariableNode> lvnList, InsnList insnList, // final AbstractInsnNode insnNode, int idx) { // Validate.notNull(insnList); // Validate.notNull(insnNode); // Validate.isTrue(idx >= 0); // // int insnIdx = insnList.indexOf(insnNode); // Validate.isTrue(insnIdx != -1); // // lvnList = lvnList.stream() // .filter(lvn -> lvn.index == idx) // filter to lvns at the index we want // .filter(lvn -> { // filter to lvns that's scope starts before the instruction we want // AbstractInsnNode currentInsnNode = insnNode.getPrevious(); // while (currentInsnNode != null) { // if (currentInsnNode == lvn.start) { // return true; // } // currentInsnNode = currentInsnNode.getPrevious(); // } // return false; // }) // .filter(lvn -> { // filter to lvns that's scope stops after the instruction we want // AbstractInsnNode currentInsnNode = insnNode.getNext(); // while (currentInsnNode != null) { // if (currentInsnNode == lvn.end) { // return true; // } // currentInsnNode = currentInsnNode.getNext(); // } // return false; // }) // .collect(Collectors.toList()); // // // // If we don't have any LVNs at this point, return null // if (lvnList.isEmpty()) { // return null; // } // // // // Should this be a list or should it always be a single entry? The problem is that there's nothing stopping multiple LVN's coming // // back for some instruction+lvt_index combination. // // // // The one thing we can be sure of at this point is that IF WE GET BACK MULTIPLE LVNs, THEY MUST OVERLAP AT SOME POINT. // // // The assumption at this point is... // // 1. LVNs are scoped such that the index of start label is BEFORE the index of the end label // // 2. LVNs must fully overlap, meaning that they can't go past each other's boundaries // // 3. LVNs can end at the same label, but they can't start at the same label // // e.g. not allowed // // x-----------x // // x--------x // // e.g. allowed // // x-----------x // // x--------x // // e.g. allowed // // x--------x // // x-----------x // // e.g. not allowed // // x--------x // // x-----------x // // // // Error out if you spot this -- someone will eventually report it and it'll get fixed // // // the following blocks of code are far from efficient, but they're easily readable/understandable // for (LocalVariableNode lvn : lvnList) { // test condition 1 // int start = insnList.indexOf(lvn.start); // int end = insnList.indexOf(lvn.end); // Validate.validState(end > start); // } // // for (LocalVariableNode lvnTester : lvnList) { // test condition 2 and 3 // int startTester = insnList.indexOf(lvnTester.start); // int endTester = insnList.indexOf(lvnTester.end); // Range rangeTester = Range.between(startTester, endTester); // // for (LocalVariableNode lvnTestee : lvnList) { // if (lvnTester == lvnTestee) { // continue; // } // // int startTestee = insnList.indexOf(lvnTestee.start); // int endTestee = insnList.indexOf(lvnTestee.end); // Range rangeTestee = Range.between(startTestee, endTestee); // // Range intersectRange = rangeTester.intersectionWith(rangeTestee); // Validate.validState(intersectRange.equals(rangeTester) || intersectRange.equals(rangeTestee)); // test condition 2 // // Validate.validState(rangeTester.getMinimum() != rangeTestee.getMinimum()); // test condition 3 // } // } // // // // Given that all the above assumptions are correct, the LVN with the smallest range will be the correct one. It's the one that's // // most tightly scoped around the instruction. // // e.g. // // x------------i----x // // x--------i-x // // x---i-x // // return Collections.min(lvnList, (o1, o2) -> { // int o1Len = insnList.indexOf(o1.end) - insnList.indexOf(o1.start); // int o2Len = insnList.indexOf(o2.end) - insnList.indexOf(o2.start); // return Integer.compare(o1Len, o2Len); // }); // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SerializationDetailer.java import static com.offbynull.coroutines.instrumenter.asm.SearchUtils.findLocalVariableNodeForInstruction; import java.util.Locale; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.lang3.Validate; import org.objectweb.asm.Type; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.BasicValue; // container[4] has local variables that are Objects // container[5] has operands that are bytes/shorts/ints // container[6] has operands that are floats // container[7] has operands that are longs // container[8] has operands that are doubles // container[9] has operands that are Objects detailLocals(cp, methodNode, output); detailOperands(cp, output); output.append('\n'); } output.append('\n'); } private void detailLocals(ContinuationPoint cp, MethodNode methodNode, StringBuilder output) { int intIdx = 0; int floatIdx = 0; int doubleIdx = 0; int longIdx = 0; int objectIdx = 0; for (int j = 0; j < cp.getFrame().getLocals(); j++) { BasicValue local = cp.getFrame().getLocal(j); if (local.getType() == null) { // unused in frame, so skip over it continue; }
LocalVariableNode lvn = findLocalVariableNodeForInstruction(
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/OperandStackStateGenerators.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/DebugGenerators.java // public enum MarkerType { // /** // * Generate no instructions. // */ // NONE, // /** // * Generate instructions to load text as string constant and immediately pop it off the stack. // */ // CONSTANT, // /** // * Generate instructions to print text to standard out. // */ // STDOUT // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/DebugGenerators.java // public static InsnList debugMarker(MarkerType markerType, String text) { // Validate.notNull(markerType); // Validate.notNull(text); // // InsnList ret = new InsnList(); // // switch (markerType) { // case NONE: // break; // case CONSTANT: // ret.add(new LdcInsnNode(text)); // ret.add(new InsnNode(Opcodes.POP)); // break; // case STDOUT: // ret.add(new FieldInsnNode(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;")); // ret.add(new LdcInsnNode(text)); // ret.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false)); // break; // default: // throw new IllegalStateException(); // } // // return ret; // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java // public static InsnList merge(Object... insns) { // Validate.notNull(insns); // Validate.noNullElements(insns); // // InsnList ret = new InsnList(); // for (Object insn : insns) { // if (insn instanceof AbstractInsnNode) { // // add single instruction // AbstractInsnNode insnNode = (AbstractInsnNode) insn; // ret.add(insnNode); // } else if (insn instanceof InsnList) { // // add instruction list // InsnList insnList = (InsnList) insn; // for (int i = 0; i < insnList.size(); i++) { // Validate.notNull(insnList.get(i)); // } // ret.add((InsnList) insn); // } else if (insn instanceof InstructionGenerator) { // // generate conditional merger instruction list and add // InsnList insnList = ((InstructionGenerator) insn).generate(); // for (int i = 0; i < insnList.size(); i++) { // Validate.notNull(insnList.get(i)); // } // ret.add(insnList); // } else { // // unrecognized // throw new IllegalArgumentException(); // } // } // // return ret; // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java // public static ConditionalMerger mergeIf(boolean condition, Supplier<Object[]> insnsSupplier) { // Validate.notNull(insnsSupplier); // // ConditionalMerger merger = new ConditionalMerger(); // return merger.mergeIf(condition, insnsSupplier); // }
import org.objectweb.asm.tree.analysis.BasicValue; import org.objectweb.asm.tree.analysis.Frame; import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import com.offbynull.coroutines.instrumenter.generators.DebugGenerators.MarkerType; import static com.offbynull.coroutines.instrumenter.generators.DebugGenerators.debugMarker; import static com.offbynull.coroutines.instrumenter.generators.GenericGenerators.merge; import static com.offbynull.coroutines.instrumenter.generators.GenericGenerators.mergeIf; import org.apache.commons.lang3.Validate; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode;
switch (type.getSort()) { case Type.BOOLEAN: case Type.BYTE: case Type.SHORT: case Type.CHAR: case Type.INT: intsCounter++; break; case Type.FLOAT: floatsCounter++; break; case Type.LONG: longsCounter++; break; case Type.DOUBLE: doublesCounter++; break; case Type.ARRAY: case Type.OBJECT: objectsCounter++; break; case Type.METHOD: case Type.VOID: default: throw new IllegalArgumentException(); } } // Restore the stack
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/DebugGenerators.java // public enum MarkerType { // /** // * Generate no instructions. // */ // NONE, // /** // * Generate instructions to load text as string constant and immediately pop it off the stack. // */ // CONSTANT, // /** // * Generate instructions to print text to standard out. // */ // STDOUT // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/DebugGenerators.java // public static InsnList debugMarker(MarkerType markerType, String text) { // Validate.notNull(markerType); // Validate.notNull(text); // // InsnList ret = new InsnList(); // // switch (markerType) { // case NONE: // break; // case CONSTANT: // ret.add(new LdcInsnNode(text)); // ret.add(new InsnNode(Opcodes.POP)); // break; // case STDOUT: // ret.add(new FieldInsnNode(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;")); // ret.add(new LdcInsnNode(text)); // ret.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false)); // break; // default: // throw new IllegalStateException(); // } // // return ret; // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java // public static InsnList merge(Object... insns) { // Validate.notNull(insns); // Validate.noNullElements(insns); // // InsnList ret = new InsnList(); // for (Object insn : insns) { // if (insn instanceof AbstractInsnNode) { // // add single instruction // AbstractInsnNode insnNode = (AbstractInsnNode) insn; // ret.add(insnNode); // } else if (insn instanceof InsnList) { // // add instruction list // InsnList insnList = (InsnList) insn; // for (int i = 0; i < insnList.size(); i++) { // Validate.notNull(insnList.get(i)); // } // ret.add((InsnList) insn); // } else if (insn instanceof InstructionGenerator) { // // generate conditional merger instruction list and add // InsnList insnList = ((InstructionGenerator) insn).generate(); // for (int i = 0; i < insnList.size(); i++) { // Validate.notNull(insnList.get(i)); // } // ret.add(insnList); // } else { // // unrecognized // throw new IllegalArgumentException(); // } // } // // return ret; // } // // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java // public static ConditionalMerger mergeIf(boolean condition, Supplier<Object[]> insnsSupplier) { // Validate.notNull(insnsSupplier); // // ConditionalMerger merger = new ConditionalMerger(); // return merger.mergeIf(condition, insnsSupplier); // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/OperandStackStateGenerators.java import org.objectweb.asm.tree.analysis.BasicValue; import org.objectweb.asm.tree.analysis.Frame; import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import com.offbynull.coroutines.instrumenter.generators.DebugGenerators.MarkerType; import static com.offbynull.coroutines.instrumenter.generators.DebugGenerators.debugMarker; import static com.offbynull.coroutines.instrumenter.generators.GenericGenerators.merge; import static com.offbynull.coroutines.instrumenter.generators.GenericGenerators.mergeIf; import org.apache.commons.lang3.Validate; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; switch (type.getSort()) { case Type.BOOLEAN: case Type.BYTE: case Type.SHORT: case Type.CHAR: case Type.INT: intsCounter++; break; case Type.FLOAT: floatsCounter++; break; case Type.LONG: longsCounter++; break; case Type.DOUBLE: doublesCounter++; break; case Type.ARRAY: case Type.OBJECT: objectsCounter++; break; case Type.METHOD: case Type.VOID: default: throw new IllegalArgumentException(); } } // Restore the stack
ret.add(debugMarker(markerType, "Loading stack items"));
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/FileSystemClassInformationRepository.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/InternalUtils.java // static ClassInformation getClassInformation(final InputStream is) throws IOException { // ClassReader classReader = new ClassReader(is); // String name = classReader.getClassName(); // // String superName = classReader.getSuperName(); // String[] interfaces = classReader.getInterfaces(); // boolean interfaceMarker = (classReader.getAccess() & Opcodes.ACC_INTERFACE) != 0; // // return new ClassInformation(name, superName, Arrays.asList(interfaces), interfaceMarker); // }
import static com.offbynull.coroutines.instrumenter.asm.InternalUtils.getClassInformation; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.compress.archivers.jar.JarArchiveEntry; import org.apache.commons.compress.archivers.jar.JarArchiveInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.Validate;
Validate.notNull(directory); Validate.isTrue(directory.isDirectory()); for (File file : FileUtils.listFiles(directory, new String[] {"class"}, true)) { if (!file.getName().endsWith(".class")) { continue; } try (InputStream is = new FileInputStream(file)) { populateSuperClassMapping(is); } } } private void addJar(File file) throws IOException { Validate.notNull(file); Validate.isTrue(file.isFile()); try (FileInputStream fis = new FileInputStream(file); JarArchiveInputStream jais = new JarArchiveInputStream(fis)) { JarArchiveEntry entry; while ((entry = jais.getNextJarEntry()) != null) { if (!entry.getName().endsWith(".class") || entry.isDirectory()) { continue; } populateSuperClassMapping(jais); } } } private void populateSuperClassMapping(final InputStream is) throws IOException {
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/InternalUtils.java // static ClassInformation getClassInformation(final InputStream is) throws IOException { // ClassReader classReader = new ClassReader(is); // String name = classReader.getClassName(); // // String superName = classReader.getSuperName(); // String[] interfaces = classReader.getInterfaces(); // boolean interfaceMarker = (classReader.getAccess() & Opcodes.ACC_INTERFACE) != 0; // // return new ClassInformation(name, superName, Arrays.asList(interfaces), interfaceMarker); // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/FileSystemClassInformationRepository.java import static com.offbynull.coroutines.instrumenter.asm.InternalUtils.getClassInformation; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.compress.archivers.jar.JarArchiveEntry; import org.apache.commons.compress.archivers.jar.JarArchiveInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.Validate; Validate.notNull(directory); Validate.isTrue(directory.isDirectory()); for (File file : FileUtils.listFiles(directory, new String[] {"class"}, true)) { if (!file.getName().endsWith(".class")) { continue; } try (InputStream is = new FileInputStream(file)) { populateSuperClassMapping(is); } } } private void addJar(File file) throws IOException { Validate.notNull(file); Validate.isTrue(file.isFile()); try (FileInputStream fis = new FileInputStream(file); JarArchiveInputStream jais = new JarArchiveInputStream(fis)) { JarArchiveEntry entry; while ((entry = jais.getNextJarEntry()) != null) { if (!entry.getName().endsWith(".class") || entry.isDirectory()) { continue; } populateSuperClassMapping(jais); } } } private void populateSuperClassMapping(final InputStream is) throws IOException {
ClassInformation ci = getClassInformation(is);
offbynull/coroutines
maven-plugin/src/test/java/com/offbynull/coroutines/mavenplugin/MainInstrumentMojoTest.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/DebugGenerators.java // public enum MarkerType { // /** // * Generate no instructions. // */ // NONE, // /** // * Generate instructions to load text as string constant and immediately pop it off the stack. // */ // CONSTANT, // /** // * Generate instructions to print text to standard out. // */ // STDOUT // }
import com.offbynull.coroutines.instrumenter.generators.DebugGenerators.MarkerType; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.maven.model.Build; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito;
package com.offbynull.coroutines.mavenplugin; public final class MainInstrumentMojoTest { private MavenProject mavenProject; private MainInstrumentMojo fixture; @BeforeEach public void setUp() throws Exception { fixture = new MainInstrumentMojo(); mavenProject = Mockito.mock(MavenProject.class); Log log = Mockito.mock(Log.class); FieldUtils.writeField(fixture, "project", mavenProject, true);
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/DebugGenerators.java // public enum MarkerType { // /** // * Generate no instructions. // */ // NONE, // /** // * Generate instructions to load text as string constant and immediately pop it off the stack. // */ // CONSTANT, // /** // * Generate instructions to print text to standard out. // */ // STDOUT // } // Path: maven-plugin/src/test/java/com/offbynull/coroutines/mavenplugin/MainInstrumentMojoTest.java import com.offbynull.coroutines.instrumenter.generators.DebugGenerators.MarkerType; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.maven.model.Build; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; package com.offbynull.coroutines.mavenplugin; public final class MainInstrumentMojoTest { private MavenProject mavenProject; private MainInstrumentMojo fixture; @BeforeEach public void setUp() throws Exception { fixture = new MainInstrumentMojo(); mavenProject = Mockito.mock(MavenProject.class); Log log = Mockito.mock(Log.class); FieldUtils.writeField(fixture, "project", mavenProject, true);
FieldUtils.writeField(fixture, "markerType", MarkerType.NONE, true);
offbynull/coroutines
maven-plugin/src/test/java/com/offbynull/coroutines/mavenplugin/TestInstrumentMojoTest.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/DebugGenerators.java // public enum MarkerType { // /** // * Generate no instructions. // */ // NONE, // /** // * Generate instructions to load text as string constant and immediately pop it off the stack. // */ // CONSTANT, // /** // * Generate instructions to print text to standard out. // */ // STDOUT // }
import com.offbynull.coroutines.instrumenter.generators.DebugGenerators.MarkerType; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.maven.model.Build; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito;
package com.offbynull.coroutines.mavenplugin; public final class TestInstrumentMojoTest { private MavenProject mavenProject; private TestInstrumentMojo fixture; @BeforeEach public void setUp() throws Exception { fixture = new TestInstrumentMojo(); mavenProject = Mockito.mock(MavenProject.class); Log log = Mockito.mock(Log.class); FieldUtils.writeField(fixture, "project", mavenProject, true);
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/DebugGenerators.java // public enum MarkerType { // /** // * Generate no instructions. // */ // NONE, // /** // * Generate instructions to load text as string constant and immediately pop it off the stack. // */ // CONSTANT, // /** // * Generate instructions to print text to standard out. // */ // STDOUT // } // Path: maven-plugin/src/test/java/com/offbynull/coroutines/mavenplugin/TestInstrumentMojoTest.java import com.offbynull.coroutines.instrumenter.generators.DebugGenerators.MarkerType; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.maven.model.Build; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; package com.offbynull.coroutines.mavenplugin; public final class TestInstrumentMojoTest { private MavenProject mavenProject; private TestInstrumentMojo fixture; @BeforeEach public void setUp() throws Exception { fixture = new TestInstrumentMojo(); mavenProject = Mockito.mock(MavenProject.class); Log log = Mockito.mock(Log.class); FieldUtils.writeField(fixture, "project", mavenProject, true);
FieldUtils.writeField(fixture, "markerType", MarkerType.NONE, true);
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // }
import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.reflect.MethodUtils; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LineNumberNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TableSwitchInsnNode; import org.objectweb.asm.tree.TryCatchBlockNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode;
/** * Generates instruction to push a string constant on to the stack. * @param s string constant to push * @return instructions to push a string constant * @throws NullPointerException if any argument is {@code null} */ public static InsnList loadStringConst(String s) { Validate.notNull(s); InsnList ret = new InsnList(); ret.add(new LdcInsnNode(s)); return ret; } /** * Generates instruction to push a null on to the stack. * @return instructions to push a null */ public static InsnList loadNull() { InsnList ret = new InsnList(); ret.add(new InsnNode(Opcodes.ACONST_NULL)); return ret; } /** * Copies a local variable on to the stack. * @param variable variable within the local variable table to load from * @return instructions to load a local variable on to the stack * @throws NullPointerException if any argument is {@code null} * @throws IllegalArgumentException if {@code variable} has been released */
// Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/VariableTable.java // public final class Variable { // private Type type; // private int index; // private boolean used; // // private Variable(Type type, int index, boolean used) { // this.type = type; // this.index = index; // this.used = used; // } // // /** // * Get the type of this local variable table entry. // * @return type of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public Type getType() { // Validate.isTrue(used); // return type; // } // // /** // * Get the index of this entry within the local variable table. // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public int getIndex() { // Validate.isTrue(used); // return index; // } // // /** // * Returns {@code true} if this object hasn't been released. // * @see VariableTable#releaseExtra(com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable) // // * @return index of this entry // * @throws IllegalArgumentException if this {@link Variable} has been released // */ // public boolean isUsed() { // return used; // } // // private VariableTable getParent() { // return VariableTable.this; // } // } // Path: instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java import com.offbynull.coroutines.instrumenter.asm.VariableTable.Variable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.reflect.MethodUtils; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LineNumberNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TableSwitchInsnNode; import org.objectweb.asm.tree.TryCatchBlockNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; /** * Generates instruction to push a string constant on to the stack. * @param s string constant to push * @return instructions to push a string constant * @throws NullPointerException if any argument is {@code null} */ public static InsnList loadStringConst(String s) { Validate.notNull(s); InsnList ret = new InsnList(); ret.add(new LdcInsnNode(s)); return ret; } /** * Generates instruction to push a null on to the stack. * @return instructions to push a null */ public static InsnList loadNull() { InsnList ret = new InsnList(); ret.add(new InsnNode(Opcodes.ACONST_NULL)); return ret; } /** * Copies a local variable on to the stack. * @param variable variable within the local variable table to load from * @return instructions to load a local variable on to the stack * @throws NullPointerException if any argument is {@code null} * @throws IllegalArgumentException if {@code variable} has been released */
public static InsnList loadVar(Variable variable) {
naomiHauret/OdysseeDesMaths
core/src/com/odysseedesmaths/minigames/arriveeremarquable/map/Case.java
// Path: core/src/com/odysseedesmaths/minigames/arriveeremarquable/entities/Entity.java // public abstract class Entity { // private ArriveeRemarquable minigame; // private Case maCase; // // public Entity(ArriveeRemarquable minigame, Case c) { // this.minigame = minigame; // this.maCase = c; // } // // public Entity(ArriveeRemarquable minigame) { // this(minigame, null); // } // // public Case getCase() { // return maCase; // } // // public void setCase(Case c) { // if (getCase() != null) { // getCase().free(); // } // maCase = c; // } // // public ArriveeRemarquable getMinigame() { // return minigame; // } // }
import com.odysseedesmaths.minigames.arriveeremarquable.entities.Entity;
package com.odysseedesmaths.minigames.arriveeremarquable.map; public class Case { public final int i; public final int j; private final boolean obstacle;
// Path: core/src/com/odysseedesmaths/minigames/arriveeremarquable/entities/Entity.java // public abstract class Entity { // private ArriveeRemarquable minigame; // private Case maCase; // // public Entity(ArriveeRemarquable minigame, Case c) { // this.minigame = minigame; // this.maCase = c; // } // // public Entity(ArriveeRemarquable minigame) { // this(minigame, null); // } // // public Case getCase() { // return maCase; // } // // public void setCase(Case c) { // if (getCase() != null) { // getCase().free(); // } // maCase = c; // } // // public ArriveeRemarquable getMinigame() { // return minigame; // } // } // Path: core/src/com/odysseedesmaths/minigames/arriveeremarquable/map/Case.java import com.odysseedesmaths.minigames.arriveeremarquable.entities.Entity; package com.odysseedesmaths.minigames.arriveeremarquable.map; public class Case { public final int i; public final int j; private final boolean obstacle;
private Entity entity;
naomiHauret/OdysseeDesMaths
core/src/com/odysseedesmaths/dialogs/SimpleDialog.java
// Path: core/src/com/odysseedesmaths/util/XMLSequencialReader.java // public abstract class XMLSequencialReader { // // protected Document document; // protected Node currentNode; // // public XMLSequencialReader(String xmlFilePath) { // try { // DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // DocumentBuilder builder = factory.newDocumentBuilder(); // document = builder.parse(Gdx.files.internal(xmlFilePath).read()); // currentNode = initCurrentNode(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public Node goToFirstChild(Node node, String targetNodeName, boolean processing) { // Node result = node.getFirstChild(); // if (result == null) return null; // String nodeName = processing ? process(result) : result.getNodeName(); // return nodeName.equals(targetNodeName) ? result : goToNextSibling(result, targetNodeName, processing); // } // // public Node goToNextSibling(Node node, String targetNodeName, boolean processing) { // Node result = node; // String nodeName = ""; // do { // result = result.getNextSibling(); // if (result != null) nodeName = processing ? process(result) : result.getNodeName(); // } while (result != null && !nodeName.equals(targetNodeName)); // return result; // } // // public abstract Node initCurrentNode(); // public abstract String process(Node node); // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.utils.Align; import com.odysseedesmaths.*; import com.odysseedesmaths.util.XMLSequencialReader; import org.w3c.dom.Element; import org.w3c.dom.Node;
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { return true; } @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (!displayAction.isFinished()) { displayAction.finish(); } else if (reader.hasNext()) { reader.next(); } else { for (TextButton endButton : endButtonsList) { buttonsGroup.addActor(endButton); } } } }); dialogTable.add(dialogChar).fill().padBottom(10).row(); dialogTable.add(dialogText).fill().expand(); reader = this.new SimpleDialogReader(dialogPath); } public void setText(final String text) { displayAction.reset(); displayAction.setText(text); displayAction.setDuration(text.length()/DISPLAY_SPEED); dialogText.addAction(displayAction); }
// Path: core/src/com/odysseedesmaths/util/XMLSequencialReader.java // public abstract class XMLSequencialReader { // // protected Document document; // protected Node currentNode; // // public XMLSequencialReader(String xmlFilePath) { // try { // DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // DocumentBuilder builder = factory.newDocumentBuilder(); // document = builder.parse(Gdx.files.internal(xmlFilePath).read()); // currentNode = initCurrentNode(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public Node goToFirstChild(Node node, String targetNodeName, boolean processing) { // Node result = node.getFirstChild(); // if (result == null) return null; // String nodeName = processing ? process(result) : result.getNodeName(); // return nodeName.equals(targetNodeName) ? result : goToNextSibling(result, targetNodeName, processing); // } // // public Node goToNextSibling(Node node, String targetNodeName, boolean processing) { // Node result = node; // String nodeName = ""; // do { // result = result.getNextSibling(); // if (result != null) nodeName = processing ? process(result) : result.getNodeName(); // } while (result != null && !nodeName.equals(targetNodeName)); // return result; // } // // public abstract Node initCurrentNode(); // public abstract String process(Node node); // } // Path: core/src/com/odysseedesmaths/dialogs/SimpleDialog.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.utils.Align; import com.odysseedesmaths.*; import com.odysseedesmaths.util.XMLSequencialReader; import org.w3c.dom.Element; import org.w3c.dom.Node; public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { return true; } @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (!displayAction.isFinished()) { displayAction.finish(); } else if (reader.hasNext()) { reader.next(); } else { for (TextButton endButton : endButtonsList) { buttonsGroup.addActor(endButton); } } } }); dialogTable.add(dialogChar).fill().padBottom(10).row(); dialogTable.add(dialogText).fill().expand(); reader = this.new SimpleDialogReader(dialogPath); } public void setText(final String text) { displayAction.reset(); displayAction.setText(text); displayAction.setDuration(text.length()/DISPLAY_SPEED); dialogText.addAction(displayAction); }
private class SimpleDialogReader extends XMLSequencialReader {
naomiHauret/OdysseeDesMaths
core/src/com/odysseedesmaths/pathfinding/Pathfinding.java
// Path: core/src/com/odysseedesmaths/pathfinding/util/PriorityQueue.java // public class PriorityQueue<E> { // // private Map<E,Integer> queue; // // public PriorityQueue() { // queue = new HashMap<E,Integer>(); // } // // public E get() { // E res = null; // Integer lowest = Integer.MAX_VALUE; // // for (Map.Entry<E,Integer> entry : queue.entrySet()) { // int priority = entry.getValue(); // if (priority < lowest) { // res = entry.getKey(); // lowest = priority; // } // } // // queue.remove(res); // return res; // } // // public void put(E e, Integer p) { // queue.put(e,p); // } // // public boolean isEmpty() { // return queue.isEmpty(); // } // // public boolean contains(E e) { // return queue.keySet().contains(e); // } // // }
import com.odysseedesmaths.pathfinding.util.PriorityQueue; import java.util.HashMap; import java.util.LinkedList; import java.util.Map;
package com.odysseedesmaths.pathfinding; /** * Implémentation basique de quelques algorithmes permettant de calculer des chemins dans un {@link Pathfindable}. */ public abstract class Pathfinding { /** * Algorithme de Dijkstra.<br> * Permet de calculer les chemins d'un sommet vers tous les autres sommets du graphe.<br> * Les chemins peuvent être extraits de la map des prédécesseurs avec {@link #buildPath(Map, Object, Object) buildPath}. * @param <E> le type des objets contenus dans le Pathfindable * @param g l'ensemble d'objet dans lequel rechercher les chemins * @param start le sommet de départ * @param dist la map des distances relatives au sommet de départ (<strong>contenu précédent perdu</strong>) * @param came_from la map des prédécesseurs de chaque sommet sur le chemin pour se rendre au point de départ (<strong>contenu précédent perdu</strong>) */ public static <E> void dijkstraAll(Pathfindable<E> g, E start, Map<E, Integer> dist, Map<E, E> came_from) { // Nettoyage et initialisation des map dist.clear(); came_from.clear(); dist.put(start, 0); came_from.put(start, null); // Liste priorisée des sommets à traiter, initialisée avec le départ
// Path: core/src/com/odysseedesmaths/pathfinding/util/PriorityQueue.java // public class PriorityQueue<E> { // // private Map<E,Integer> queue; // // public PriorityQueue() { // queue = new HashMap<E,Integer>(); // } // // public E get() { // E res = null; // Integer lowest = Integer.MAX_VALUE; // // for (Map.Entry<E,Integer> entry : queue.entrySet()) { // int priority = entry.getValue(); // if (priority < lowest) { // res = entry.getKey(); // lowest = priority; // } // } // // queue.remove(res); // return res; // } // // public void put(E e, Integer p) { // queue.put(e,p); // } // // public boolean isEmpty() { // return queue.isEmpty(); // } // // public boolean contains(E e) { // return queue.keySet().contains(e); // } // // } // Path: core/src/com/odysseedesmaths/pathfinding/Pathfinding.java import com.odysseedesmaths.pathfinding.util.PriorityQueue; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; package com.odysseedesmaths.pathfinding; /** * Implémentation basique de quelques algorithmes permettant de calculer des chemins dans un {@link Pathfindable}. */ public abstract class Pathfinding { /** * Algorithme de Dijkstra.<br> * Permet de calculer les chemins d'un sommet vers tous les autres sommets du graphe.<br> * Les chemins peuvent être extraits de la map des prédécesseurs avec {@link #buildPath(Map, Object, Object) buildPath}. * @param <E> le type des objets contenus dans le Pathfindable * @param g l'ensemble d'objet dans lequel rechercher les chemins * @param start le sommet de départ * @param dist la map des distances relatives au sommet de départ (<strong>contenu précédent perdu</strong>) * @param came_from la map des prédécesseurs de chaque sommet sur le chemin pour se rendre au point de départ (<strong>contenu précédent perdu</strong>) */ public static <E> void dijkstraAll(Pathfindable<E> g, E start, Map<E, Integer> dist, Map<E, E> came_from) { // Nettoyage et initialisation des map dist.clear(); came_from.clear(); dist.put(start, 0); came_from.put(start, null); // Liste priorisée des sommets à traiter, initialisée avec le départ
PriorityQueue<E> toDo = new PriorityQueue<E>();
naomiHauret/OdysseeDesMaths
core/src/com/odysseedesmaths/scenes/Scene0.java
// Path: core/src/com/odysseedesmaths/Assets.java // public class Assets { // // private Assets() {} // // private static final AnnotationAssetManager manager = new AnnotationAssetManager(); // // public static AnnotationAssetManager getManager() { // return manager; // } // // // Raccourcis pratiques // private static final String // ICONS_PATH = "textures/common/char_icons/", // DLG_PATH = "texts/dialogs/", // EXP_PATH = "texts/explanations/", // QST_PATH = "texts/questionnaires/"; // // @Asset(Texture.class) // public static final String // HERO = "textures/common/heros.png", // HEART = "textures/common/heart.png", // HEART_EMPTY = "textures/common/heart_empty.png", // VANNEBUTTON = "textures/CoffeePlumbing/vanneButton.png", // MAIN_MENU_BACKGROUND = "tower.png", // // Icones des personnages // ICON_HERO = ICONS_PATH+"hero.png", // ICON_PYLES = ICONS_PATH+"pyles.png", // ICON_AUDIB = ICONS_PATH+"audib.png", // ICON_GWENDOUILLE = ICONS_PATH+"gwendouille.png", // ICON_DIJKSTRA = ICONS_PATH+"dijkstra.png", // ICON_EDDYMALOU = ICONS_PATH+"eddymalou.png", // ICON_MARKOV = ICONS_PATH+"markov.png", // ICON_NICHOLAS = ICONS_PATH+"nicholasSaunderson.png", // ICON_PYTHAGORE = ICONS_PATH+"pythagore.png", // ICON_ROBERT = ICONS_PATH+"robertSmithn.png", // ICON_TARTAGLIA = ICONS_PATH+"tartaglia.png", // ICON_THALES = ICONS_PATH+"thales.png", // ICON_TIFOUILLE = ICONS_PATH+"tifouille.png", // ICON_VIKTOR = ICONS_PATH+"viktor.png", // ARRIVEE_REMARAQUABLE_ARCADE_MACHINE = "textures/common/arcadeMachines/arriveRemarquableArcadeMachine.png", // ACCROBRANCHE_ARCADE_MACHINE = "textures/common/arcadeMachines/accrobrancheArcadeMachine.png", // COFFEE_PLUMBING_ARCADE_MACHINE = "textures/common/arcadeMachines/CoffeePlumbingArcadeMachine.png", // ARCADE_ROOM_BACKGROUND = "textures/common/arcadeMachines/background.png"; // // // @Asset(TextureAtlas.class) // public static final String // UI_MAIN = "ui/main.atlas", // UI_ORANGE = "ui/orange.atlas", // UI_SCROLL = "ui/scroll.atlas", // KOFFEE = "textures/CoffeePlumbing/koffee.atlas"; // // // @Asset(Music.class) // public static final String // ARCADE = "music/Arcade_Machine.ogg", // MENU_MUSIC = "music/Opening.ogg", // GAME_OVER_MUSIC = "music/Game Over.ogg", // GAGNER_MUSIC = "music/Victory.ogg"; // // // public static final FileHandle // PRESS_START_2P = Gdx.files.internal("fonts/PressStart2P.ttf"), // KENPIXEL_BLOCKS = Gdx.files.internal("fonts/kenpixel_blocks.ttf"); // // // Dialogues // public static final String // DLG_ARRIVEE_1 = DLG_PATH + "dialogue01.xml", // DLG_ARRIVEE_2a = DLG_PATH + "dialogue02a.xml", // DLG_ARRIVEE_2b = DLG_PATH + "dialogue02b.xml"; // // // Explications // public static final String // EXP_ARRIVEE_1 = EXP_PATH + "arrivee1.xml"; // // // Questionnaires // public static final String // QST_ARRIVEE1 = QST_PATH + "arrivee1.xml"; // // // Scènes // @Asset(Texture.class) // public static final String // S00_CLASSE = "scenes/classe.png", // S00_TABLEAU = "scenes/tableau.png", // S00_TABLEAU_PROF = "scenes/tableauProf.png", // S00_ELEVE = "scenes/eleveDormir.png", // S01_PAYSAGE = "scenes/paysage.png", // S01_FUITE = "scenes/fuite.png", // S02_CHUTE = "scenes/trou2.png", // S02_CAVERNE = "scenes/caverne.png"; // // // /********************** // * ASSETS SPECIFIQUES * // **********************/ // // // Arrivée remarquable // private static final String ARR_PATH = "arrivee_remarquable/"; // // @Asset(TextureAtlas.class) // public static final String // ARR_ATLAS = ARR_PATH + "arrivee.atlas"; // // @Asset(Texture.class) // public static final String // ARR_DLGIMG_G1 = ARR_PATH + "dialogs_images/g1.png", // ARR_DLGIMG_G2 = ARR_PATH + "dialogs_images/g2.png", // ARR_DLGIMG_G3 = ARR_PATH + "dialogs_images/g3.png", // ARR_DLGIMG_G4 = ARR_PATH + "dialogs_images/g4.png", // ARR_DLGIMG_G5 = ARR_PATH + "dialogs_images/g5.png", // ARR_DLGIMG_G6 = ARR_PATH + "dialogs_images/g6.png", // ARR_DLGIMG_G7 = ARR_PATH + "dialogs_images/g7.png"; // // // Plongée au coeur du problème // // Accrobranche // // Coffee Plumbing // // Mauvais tournant // // Tower's destruction // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.odysseedesmaths.Assets;
package com.odysseedesmaths.scenes; public class Scene0 extends Scene { private int state; private Texture background; public Scene0 () { state = 0;
// Path: core/src/com/odysseedesmaths/Assets.java // public class Assets { // // private Assets() {} // // private static final AnnotationAssetManager manager = new AnnotationAssetManager(); // // public static AnnotationAssetManager getManager() { // return manager; // } // // // Raccourcis pratiques // private static final String // ICONS_PATH = "textures/common/char_icons/", // DLG_PATH = "texts/dialogs/", // EXP_PATH = "texts/explanations/", // QST_PATH = "texts/questionnaires/"; // // @Asset(Texture.class) // public static final String // HERO = "textures/common/heros.png", // HEART = "textures/common/heart.png", // HEART_EMPTY = "textures/common/heart_empty.png", // VANNEBUTTON = "textures/CoffeePlumbing/vanneButton.png", // MAIN_MENU_BACKGROUND = "tower.png", // // Icones des personnages // ICON_HERO = ICONS_PATH+"hero.png", // ICON_PYLES = ICONS_PATH+"pyles.png", // ICON_AUDIB = ICONS_PATH+"audib.png", // ICON_GWENDOUILLE = ICONS_PATH+"gwendouille.png", // ICON_DIJKSTRA = ICONS_PATH+"dijkstra.png", // ICON_EDDYMALOU = ICONS_PATH+"eddymalou.png", // ICON_MARKOV = ICONS_PATH+"markov.png", // ICON_NICHOLAS = ICONS_PATH+"nicholasSaunderson.png", // ICON_PYTHAGORE = ICONS_PATH+"pythagore.png", // ICON_ROBERT = ICONS_PATH+"robertSmithn.png", // ICON_TARTAGLIA = ICONS_PATH+"tartaglia.png", // ICON_THALES = ICONS_PATH+"thales.png", // ICON_TIFOUILLE = ICONS_PATH+"tifouille.png", // ICON_VIKTOR = ICONS_PATH+"viktor.png", // ARRIVEE_REMARAQUABLE_ARCADE_MACHINE = "textures/common/arcadeMachines/arriveRemarquableArcadeMachine.png", // ACCROBRANCHE_ARCADE_MACHINE = "textures/common/arcadeMachines/accrobrancheArcadeMachine.png", // COFFEE_PLUMBING_ARCADE_MACHINE = "textures/common/arcadeMachines/CoffeePlumbingArcadeMachine.png", // ARCADE_ROOM_BACKGROUND = "textures/common/arcadeMachines/background.png"; // // // @Asset(TextureAtlas.class) // public static final String // UI_MAIN = "ui/main.atlas", // UI_ORANGE = "ui/orange.atlas", // UI_SCROLL = "ui/scroll.atlas", // KOFFEE = "textures/CoffeePlumbing/koffee.atlas"; // // // @Asset(Music.class) // public static final String // ARCADE = "music/Arcade_Machine.ogg", // MENU_MUSIC = "music/Opening.ogg", // GAME_OVER_MUSIC = "music/Game Over.ogg", // GAGNER_MUSIC = "music/Victory.ogg"; // // // public static final FileHandle // PRESS_START_2P = Gdx.files.internal("fonts/PressStart2P.ttf"), // KENPIXEL_BLOCKS = Gdx.files.internal("fonts/kenpixel_blocks.ttf"); // // // Dialogues // public static final String // DLG_ARRIVEE_1 = DLG_PATH + "dialogue01.xml", // DLG_ARRIVEE_2a = DLG_PATH + "dialogue02a.xml", // DLG_ARRIVEE_2b = DLG_PATH + "dialogue02b.xml"; // // // Explications // public static final String // EXP_ARRIVEE_1 = EXP_PATH + "arrivee1.xml"; // // // Questionnaires // public static final String // QST_ARRIVEE1 = QST_PATH + "arrivee1.xml"; // // // Scènes // @Asset(Texture.class) // public static final String // S00_CLASSE = "scenes/classe.png", // S00_TABLEAU = "scenes/tableau.png", // S00_TABLEAU_PROF = "scenes/tableauProf.png", // S00_ELEVE = "scenes/eleveDormir.png", // S01_PAYSAGE = "scenes/paysage.png", // S01_FUITE = "scenes/fuite.png", // S02_CHUTE = "scenes/trou2.png", // S02_CAVERNE = "scenes/caverne.png"; // // // /********************** // * ASSETS SPECIFIQUES * // **********************/ // // // Arrivée remarquable // private static final String ARR_PATH = "arrivee_remarquable/"; // // @Asset(TextureAtlas.class) // public static final String // ARR_ATLAS = ARR_PATH + "arrivee.atlas"; // // @Asset(Texture.class) // public static final String // ARR_DLGIMG_G1 = ARR_PATH + "dialogs_images/g1.png", // ARR_DLGIMG_G2 = ARR_PATH + "dialogs_images/g2.png", // ARR_DLGIMG_G3 = ARR_PATH + "dialogs_images/g3.png", // ARR_DLGIMG_G4 = ARR_PATH + "dialogs_images/g4.png", // ARR_DLGIMG_G5 = ARR_PATH + "dialogs_images/g5.png", // ARR_DLGIMG_G6 = ARR_PATH + "dialogs_images/g6.png", // ARR_DLGIMG_G7 = ARR_PATH + "dialogs_images/g7.png"; // // // Plongée au coeur du problème // // Accrobranche // // Coffee Plumbing // // Mauvais tournant // // Tower's destruction // } // Path: core/src/com/odysseedesmaths/scenes/Scene0.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.odysseedesmaths.Assets; package com.odysseedesmaths.scenes; public class Scene0 extends Scene { private int state; private Texture background; public Scene0 () { state = 0;
background = Assets.getManager().get(Assets.S00_CLASSE, Texture.class);
naomiHauret/OdysseeDesMaths
core/src/com/odysseedesmaths/minigames/coffeePlumbing/CoffeePlumbing.java
// Path: core/src/com/odysseedesmaths/Musique.java // public class Musique { // private static Music currentMusic = null; // private static String currentFile = null; // private static int volume; // // private Musique() {} // // public static Music getCurrent() { // return currentMusic; // } // // public static void setCurrent(String fileName) { // if (currentMusic != null) stop(); // // currentFile = fileName; // // if (!Assets.getManager().isLoaded(fileName)) { // Assets.getManager().load(fileName, Music.class); // Assets.getManager().finishLoadingAsset(fileName); // } // currentMusic = Assets.getManager().get(fileName, Music.class); // } // // public static void play() { // currentMusic.setLooping(true); // setVolume(volume); // currentMusic.play(); // } // // public static void pause() { // currentMusic.pause(); // } // // public static void stop() { // Assets.getManager().unload(currentFile); // currentMusic.dispose(); // } // // public static boolean isPlaying() { // return (currentMusic != null) && currentMusic.isPlaying(); // } // // public static void setVolume(int volumePercent) { // if (volumePercent>100 || volumePercent<0) { // throw new IllegalArgumentException("Pourcentage incorrect : " + volumePercent); // } else { // volume = volumePercent; // if (currentMusic != null) currentMusic.setVolume(volume / 100f); // } // } // } // // Path: core/src/com/odysseedesmaths/OdysseeDesMaths.java // public class OdysseeDesMaths extends Game { // private static Settings settings; // // public SpriteBatch batcher; // // private ModeSceneScreen modeScene = null; // private SavesManager savesManager; // // public static Settings getSettings() { // if (settings == null) { // settings = new Settings(); // } // return settings; // } // // @Override // public void create() { // Assets.getManager().load(Assets.class); // Assets.getManager().finishLoading(); // // Musique.setVolume(getSettings().isMusicMuted() ? 0 : 100); // // batcher = new SpriteBatch(); // setScreen(new GameChoiceMenu(this)); // } // // public ModeSceneScreen getModeScene() { // if (modeScene == null) { // this.modeScene = new ModeSceneScreen(this); // } // modeScene.returnToScene(); // Pour ne pas retourner sur le menu // return modeScene; // } // // public SavesManager getSavesManager() { // if (savesManager == null) { // this.savesManager = new SavesManager(); // } // return savesManager; // } // // /* Ces méthodes permettent d'éviter d'instancier plusieurs fois des écrans // toujours identiques. // On peut faire de même pour chaque jeu, où vérifier qu'ils sont détruits lorsqu'on les // quitte. // */ // // public void startGame() { // if (savesManager.getCurrentSave().isEmpty()) { // setScreen(new NewSave(this)); // } else { // setScreen(getModeScene()); // } // } // } // // Path: core/src/com/odysseedesmaths/minigames/MiniGame.java // public abstract class MiniGame implements Screen { // // public enum State {RUNNING, PAUSED, GAME_OVER, WIN} // protected State currentState; // // protected OdysseeDesMaths game; // public Screen currentScreen; // // public MiniGame(OdysseeDesMaths game) { // this.game = game; // } // // public void setScreen(Screen screen) { // if (currentScreen != null) currentScreen.dispose(); // currentScreen = screen; // } // // public State getState() { // return currentState; // } // // public void setState(State newState) { // currentState = newState; // } // // public OdysseeDesMaths getGame() { // return game; // } // // @Override // public void show() { // currentScreen.show(); // } // // @Override // public void render(float delta) { // currentScreen.render(delta); // } // // @Override // public void resize(int width, int height) { // currentScreen.resize(width, height); // } // // @Override // public void pause() { // currentScreen.pause(); // } // // @Override // public void resume() { // currentScreen.resume(); // } // // @Override // public void hide() { // currentScreen.hide(); // } // // @Override // public void dispose() { // currentScreen.dispose(); // } // // public void returnToMainMenu() { // game.setScreen(new MenuPrincipal(game)); // } // }
import com.odysseedesmaths.Musique; import com.odysseedesmaths.OdysseeDesMaths; import com.odysseedesmaths.minigames.MiniGame;
package com.odysseedesmaths.minigames.coffeePlumbing; /** * Created by trilunaire on 08/02/16. */ public class CoffeePlumbing extends MiniGame { private String currentLevel; private PipesScreen ui;
// Path: core/src/com/odysseedesmaths/Musique.java // public class Musique { // private static Music currentMusic = null; // private static String currentFile = null; // private static int volume; // // private Musique() {} // // public static Music getCurrent() { // return currentMusic; // } // // public static void setCurrent(String fileName) { // if (currentMusic != null) stop(); // // currentFile = fileName; // // if (!Assets.getManager().isLoaded(fileName)) { // Assets.getManager().load(fileName, Music.class); // Assets.getManager().finishLoadingAsset(fileName); // } // currentMusic = Assets.getManager().get(fileName, Music.class); // } // // public static void play() { // currentMusic.setLooping(true); // setVolume(volume); // currentMusic.play(); // } // // public static void pause() { // currentMusic.pause(); // } // // public static void stop() { // Assets.getManager().unload(currentFile); // currentMusic.dispose(); // } // // public static boolean isPlaying() { // return (currentMusic != null) && currentMusic.isPlaying(); // } // // public static void setVolume(int volumePercent) { // if (volumePercent>100 || volumePercent<0) { // throw new IllegalArgumentException("Pourcentage incorrect : " + volumePercent); // } else { // volume = volumePercent; // if (currentMusic != null) currentMusic.setVolume(volume / 100f); // } // } // } // // Path: core/src/com/odysseedesmaths/OdysseeDesMaths.java // public class OdysseeDesMaths extends Game { // private static Settings settings; // // public SpriteBatch batcher; // // private ModeSceneScreen modeScene = null; // private SavesManager savesManager; // // public static Settings getSettings() { // if (settings == null) { // settings = new Settings(); // } // return settings; // } // // @Override // public void create() { // Assets.getManager().load(Assets.class); // Assets.getManager().finishLoading(); // // Musique.setVolume(getSettings().isMusicMuted() ? 0 : 100); // // batcher = new SpriteBatch(); // setScreen(new GameChoiceMenu(this)); // } // // public ModeSceneScreen getModeScene() { // if (modeScene == null) { // this.modeScene = new ModeSceneScreen(this); // } // modeScene.returnToScene(); // Pour ne pas retourner sur le menu // return modeScene; // } // // public SavesManager getSavesManager() { // if (savesManager == null) { // this.savesManager = new SavesManager(); // } // return savesManager; // } // // /* Ces méthodes permettent d'éviter d'instancier plusieurs fois des écrans // toujours identiques. // On peut faire de même pour chaque jeu, où vérifier qu'ils sont détruits lorsqu'on les // quitte. // */ // // public void startGame() { // if (savesManager.getCurrentSave().isEmpty()) { // setScreen(new NewSave(this)); // } else { // setScreen(getModeScene()); // } // } // } // // Path: core/src/com/odysseedesmaths/minigames/MiniGame.java // public abstract class MiniGame implements Screen { // // public enum State {RUNNING, PAUSED, GAME_OVER, WIN} // protected State currentState; // // protected OdysseeDesMaths game; // public Screen currentScreen; // // public MiniGame(OdysseeDesMaths game) { // this.game = game; // } // // public void setScreen(Screen screen) { // if (currentScreen != null) currentScreen.dispose(); // currentScreen = screen; // } // // public State getState() { // return currentState; // } // // public void setState(State newState) { // currentState = newState; // } // // public OdysseeDesMaths getGame() { // return game; // } // // @Override // public void show() { // currentScreen.show(); // } // // @Override // public void render(float delta) { // currentScreen.render(delta); // } // // @Override // public void resize(int width, int height) { // currentScreen.resize(width, height); // } // // @Override // public void pause() { // currentScreen.pause(); // } // // @Override // public void resume() { // currentScreen.resume(); // } // // @Override // public void hide() { // currentScreen.hide(); // } // // @Override // public void dispose() { // currentScreen.dispose(); // } // // public void returnToMainMenu() { // game.setScreen(new MenuPrincipal(game)); // } // } // Path: core/src/com/odysseedesmaths/minigames/coffeePlumbing/CoffeePlumbing.java import com.odysseedesmaths.Musique; import com.odysseedesmaths.OdysseeDesMaths; import com.odysseedesmaths.minigames.MiniGame; package com.odysseedesmaths.minigames.coffeePlumbing; /** * Created by trilunaire on 08/02/16. */ public class CoffeePlumbing extends MiniGame { private String currentLevel; private PipesScreen ui;
public CoffeePlumbing(OdysseeDesMaths game){
MrHadiSatrio/Optional
src/test/java/com/hadisatrio/optional/OptionalShortTest.java
// Path: src/main/java/com/hadisatrio/optional/function/ShortConsumer.java // public interface ShortConsumer { // // void consume(short value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ShortSupplier.java // public interface ShortSupplier { // // short get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // }
import com.hadisatrio.optional.function.ShortConsumer; import com.hadisatrio.optional.function.ShortSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test;
/* * Copyright (C) 2016 Hadi Satrio * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.hadisatrio.optional; public class OptionalShortTest { @Test public void of() throws Exception { Assert.assertTrue(OptionalShort.of(((short) 42)).isPresent()); } @Test public void absent() throws Exception { Assert.assertFalse(OptionalShort.absent().isPresent()); } @Test public void isPresent() throws Exception { Assert.assertTrue(OptionalShort.of(((short) 42)).isPresent()); Assert.assertFalse(OptionalShort.absent().isPresent()); } @Test public void get() throws Exception { Assert.assertEquals(((short) 42), OptionalShort.of(((short) 42)).get()); try { OptionalShort.absent().get(); Assert.fail("Invoking get() on an absent optional should raise an exception."); } catch (IllegalStateException expected) { // No-op. This is the expected behaviour. } } @Test public void or() throws Exception { Assert.assertEquals(((short) 42), OptionalShort.absent().or(((short) 42))); } @Test public void orWithSupplier() throws Exception {
// Path: src/main/java/com/hadisatrio/optional/function/ShortConsumer.java // public interface ShortConsumer { // // void consume(short value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ShortSupplier.java // public interface ShortSupplier { // // short get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // } // Path: src/test/java/com/hadisatrio/optional/OptionalShortTest.java import com.hadisatrio.optional.function.ShortConsumer; import com.hadisatrio.optional.function.ShortSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test; /* * Copyright (C) 2016 Hadi Satrio * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.hadisatrio.optional; public class OptionalShortTest { @Test public void of() throws Exception { Assert.assertTrue(OptionalShort.of(((short) 42)).isPresent()); } @Test public void absent() throws Exception { Assert.assertFalse(OptionalShort.absent().isPresent()); } @Test public void isPresent() throws Exception { Assert.assertTrue(OptionalShort.of(((short) 42)).isPresent()); Assert.assertFalse(OptionalShort.absent().isPresent()); } @Test public void get() throws Exception { Assert.assertEquals(((short) 42), OptionalShort.of(((short) 42)).get()); try { OptionalShort.absent().get(); Assert.fail("Invoking get() on an absent optional should raise an exception."); } catch (IllegalStateException expected) { // No-op. This is the expected behaviour. } } @Test public void or() throws Exception { Assert.assertEquals(((short) 42), OptionalShort.absent().or(((short) 42))); } @Test public void orWithSupplier() throws Exception {
Assert.assertEquals((short) 42, OptionalShort.absent().or(new ShortSupplier() {
MrHadiSatrio/Optional
src/test/java/com/hadisatrio/optional/OptionalShortTest.java
// Path: src/main/java/com/hadisatrio/optional/function/ShortConsumer.java // public interface ShortConsumer { // // void consume(short value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ShortSupplier.java // public interface ShortSupplier { // // short get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // }
import com.hadisatrio.optional.function.ShortConsumer; import com.hadisatrio.optional.function.ShortSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test;
} @Test public void or() throws Exception { Assert.assertEquals(((short) 42), OptionalShort.absent().or(((short) 42))); } @Test public void orWithSupplier() throws Exception { Assert.assertEquals((short) 42, OptionalShort.absent().or(new ShortSupplier() { @Override public short get() { return 42; } })); } @Test public void orThrow() throws Exception { try { OptionalShort.absent().orThrow(new Exception("An exception occurred.")); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void orThrowWithSupplier() throws Exception {
// Path: src/main/java/com/hadisatrio/optional/function/ShortConsumer.java // public interface ShortConsumer { // // void consume(short value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ShortSupplier.java // public interface ShortSupplier { // // short get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // } // Path: src/test/java/com/hadisatrio/optional/OptionalShortTest.java import com.hadisatrio.optional.function.ShortConsumer; import com.hadisatrio.optional.function.ShortSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test; } @Test public void or() throws Exception { Assert.assertEquals(((short) 42), OptionalShort.absent().or(((short) 42))); } @Test public void orWithSupplier() throws Exception { Assert.assertEquals((short) 42, OptionalShort.absent().or(new ShortSupplier() { @Override public short get() { return 42; } })); } @Test public void orThrow() throws Exception { try { OptionalShort.absent().orThrow(new Exception("An exception occurred.")); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void orThrowWithSupplier() throws Exception {
final Supplier<Exception> anExceptionSupplier = new Supplier<Exception>() {
MrHadiSatrio/Optional
src/test/java/com/hadisatrio/optional/OptionalShortTest.java
// Path: src/main/java/com/hadisatrio/optional/function/ShortConsumer.java // public interface ShortConsumer { // // void consume(short value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ShortSupplier.java // public interface ShortSupplier { // // short get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // }
import com.hadisatrio.optional.function.ShortConsumer; import com.hadisatrio.optional.function.ShortSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test;
public void orThrow() throws Exception { try { OptionalShort.absent().orThrow(new Exception("An exception occurred.")); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void orThrowWithSupplier() throws Exception { final Supplier<Exception> anExceptionSupplier = new Supplier<Exception>() { @Override public Exception get() { return new Exception("An exception occurred."); } }; try { OptionalShort.absent().orThrow(anExceptionSupplier); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void ifPresent() throws Exception {
// Path: src/main/java/com/hadisatrio/optional/function/ShortConsumer.java // public interface ShortConsumer { // // void consume(short value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ShortSupplier.java // public interface ShortSupplier { // // short get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // } // Path: src/test/java/com/hadisatrio/optional/OptionalShortTest.java import com.hadisatrio.optional.function.ShortConsumer; import com.hadisatrio.optional.function.ShortSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test; public void orThrow() throws Exception { try { OptionalShort.absent().orThrow(new Exception("An exception occurred.")); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void orThrowWithSupplier() throws Exception { final Supplier<Exception> anExceptionSupplier = new Supplier<Exception>() { @Override public Exception get() { return new Exception("An exception occurred."); } }; try { OptionalShort.absent().orThrow(anExceptionSupplier); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void ifPresent() throws Exception {
OptionalShort.of(((short) 42)).ifPresent(new ShortConsumer() {
MrHadiSatrio/Optional
src/test/java/com/hadisatrio/optional/OptionalShortTest.java
// Path: src/main/java/com/hadisatrio/optional/function/ShortConsumer.java // public interface ShortConsumer { // // void consume(short value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ShortSupplier.java // public interface ShortSupplier { // // short get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // }
import com.hadisatrio.optional.function.ShortConsumer; import com.hadisatrio.optional.function.ShortSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test;
Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void ifPresent() throws Exception { OptionalShort.of(((short) 42)).ifPresent(new ShortConsumer() { @Override public void consume(short value) { Assert.assertEquals(((short) 42), value); } }); OptionalShort.absent().ifPresent(new ShortConsumer() { @Override public void consume(short value) { Assert.fail("ifPresent() on an absent optional should never call its consumer"); } }); } @Test public void ifPresentOrElse() throws Exception { OptionalShort.of(((short) 42)).ifPresentOrElse(new ShortConsumer() { @Override public void consume(short value) { Assert.assertEquals(((short) 42), value); }
// Path: src/main/java/com/hadisatrio/optional/function/ShortConsumer.java // public interface ShortConsumer { // // void consume(short value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ShortSupplier.java // public interface ShortSupplier { // // short get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // } // Path: src/test/java/com/hadisatrio/optional/OptionalShortTest.java import com.hadisatrio.optional.function.ShortConsumer; import com.hadisatrio.optional.function.ShortSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test; Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void ifPresent() throws Exception { OptionalShort.of(((short) 42)).ifPresent(new ShortConsumer() { @Override public void consume(short value) { Assert.assertEquals(((short) 42), value); } }); OptionalShort.absent().ifPresent(new ShortConsumer() { @Override public void consume(short value) { Assert.fail("ifPresent() on an absent optional should never call its consumer"); } }); } @Test public void ifPresentOrElse() throws Exception { OptionalShort.of(((short) 42)).ifPresentOrElse(new ShortConsumer() { @Override public void consume(short value) { Assert.assertEquals(((short) 42), value); }
}, new Function() {
MrHadiSatrio/Optional
src/test/java/com/hadisatrio/optional/OptionalByteTest.java
// Path: src/main/java/com/hadisatrio/optional/function/ByteConsumer.java // public interface ByteConsumer { // // void consume(byte value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ByteSupplier.java // public interface ByteSupplier { // // byte get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // }
import com.hadisatrio.optional.function.ByteConsumer; import com.hadisatrio.optional.function.ByteSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test;
/* * Copyright (C) 2016 Hadi Satrio * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.hadisatrio.optional; public class OptionalByteTest { @Test public void of() throws Exception { Assert.assertTrue(OptionalByte.of(((byte) 42)).isPresent()); } @Test public void absent() throws Exception { Assert.assertFalse(OptionalByte.absent().isPresent()); } @Test public void isPresent() throws Exception { Assert.assertTrue(OptionalByte.of(((byte) 42)).isPresent()); Assert.assertFalse(OptionalByte.absent().isPresent()); } @Test public void get() throws Exception { Assert.assertEquals(((byte) 42), OptionalByte.of(((byte) 42)).get()); try { OptionalByte.absent().get(); Assert.fail("Invoking get() on an absent optional should raise an exception."); } catch (IllegalStateException expected) { // No-op. This is the expected behaviour. } } @Test public void or() throws Exception { Assert.assertEquals(((byte) 42), OptionalByte.absent().or(((byte) 42))); } @Test public void orWithSupplier() throws Exception {
// Path: src/main/java/com/hadisatrio/optional/function/ByteConsumer.java // public interface ByteConsumer { // // void consume(byte value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ByteSupplier.java // public interface ByteSupplier { // // byte get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // } // Path: src/test/java/com/hadisatrio/optional/OptionalByteTest.java import com.hadisatrio.optional.function.ByteConsumer; import com.hadisatrio.optional.function.ByteSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test; /* * Copyright (C) 2016 Hadi Satrio * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.hadisatrio.optional; public class OptionalByteTest { @Test public void of() throws Exception { Assert.assertTrue(OptionalByte.of(((byte) 42)).isPresent()); } @Test public void absent() throws Exception { Assert.assertFalse(OptionalByte.absent().isPresent()); } @Test public void isPresent() throws Exception { Assert.assertTrue(OptionalByte.of(((byte) 42)).isPresent()); Assert.assertFalse(OptionalByte.absent().isPresent()); } @Test public void get() throws Exception { Assert.assertEquals(((byte) 42), OptionalByte.of(((byte) 42)).get()); try { OptionalByte.absent().get(); Assert.fail("Invoking get() on an absent optional should raise an exception."); } catch (IllegalStateException expected) { // No-op. This is the expected behaviour. } } @Test public void or() throws Exception { Assert.assertEquals(((byte) 42), OptionalByte.absent().or(((byte) 42))); } @Test public void orWithSupplier() throws Exception {
Assert.assertEquals((byte) 42, OptionalByte.absent().or(new ByteSupplier() {
MrHadiSatrio/Optional
src/test/java/com/hadisatrio/optional/OptionalByteTest.java
// Path: src/main/java/com/hadisatrio/optional/function/ByteConsumer.java // public interface ByteConsumer { // // void consume(byte value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ByteSupplier.java // public interface ByteSupplier { // // byte get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // }
import com.hadisatrio.optional.function.ByteConsumer; import com.hadisatrio.optional.function.ByteSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test;
} @Test public void or() throws Exception { Assert.assertEquals(((byte) 42), OptionalByte.absent().or(((byte) 42))); } @Test public void orWithSupplier() throws Exception { Assert.assertEquals((byte) 42, OptionalByte.absent().or(new ByteSupplier() { @Override public byte get() { return 42; } })); } @Test public void orThrow() throws Exception { try { OptionalByte.absent().orThrow(new Exception("An exception occurred.")); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void orThrowWithSupplier() throws Exception {
// Path: src/main/java/com/hadisatrio/optional/function/ByteConsumer.java // public interface ByteConsumer { // // void consume(byte value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ByteSupplier.java // public interface ByteSupplier { // // byte get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // } // Path: src/test/java/com/hadisatrio/optional/OptionalByteTest.java import com.hadisatrio.optional.function.ByteConsumer; import com.hadisatrio.optional.function.ByteSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test; } @Test public void or() throws Exception { Assert.assertEquals(((byte) 42), OptionalByte.absent().or(((byte) 42))); } @Test public void orWithSupplier() throws Exception { Assert.assertEquals((byte) 42, OptionalByte.absent().or(new ByteSupplier() { @Override public byte get() { return 42; } })); } @Test public void orThrow() throws Exception { try { OptionalByte.absent().orThrow(new Exception("An exception occurred.")); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void orThrowWithSupplier() throws Exception {
final Supplier<Exception> anExceptionSupplier = new Supplier<Exception>() {
MrHadiSatrio/Optional
src/test/java/com/hadisatrio/optional/OptionalByteTest.java
// Path: src/main/java/com/hadisatrio/optional/function/ByteConsumer.java // public interface ByteConsumer { // // void consume(byte value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ByteSupplier.java // public interface ByteSupplier { // // byte get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // }
import com.hadisatrio.optional.function.ByteConsumer; import com.hadisatrio.optional.function.ByteSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test;
public void orThrow() throws Exception { try { OptionalByte.absent().orThrow(new Exception("An exception occurred.")); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void orThrowWithSupplier() throws Exception { final Supplier<Exception> anExceptionSupplier = new Supplier<Exception>() { @Override public Exception get() { return new Exception("An exception occurred."); } }; try { OptionalByte.absent().orThrow(anExceptionSupplier); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void ifPresent() throws Exception {
// Path: src/main/java/com/hadisatrio/optional/function/ByteConsumer.java // public interface ByteConsumer { // // void consume(byte value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ByteSupplier.java // public interface ByteSupplier { // // byte get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // } // Path: src/test/java/com/hadisatrio/optional/OptionalByteTest.java import com.hadisatrio.optional.function.ByteConsumer; import com.hadisatrio.optional.function.ByteSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test; public void orThrow() throws Exception { try { OptionalByte.absent().orThrow(new Exception("An exception occurred.")); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void orThrowWithSupplier() throws Exception { final Supplier<Exception> anExceptionSupplier = new Supplier<Exception>() { @Override public Exception get() { return new Exception("An exception occurred."); } }; try { OptionalByte.absent().orThrow(anExceptionSupplier); Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void ifPresent() throws Exception {
OptionalByte.of(((byte) 42)).ifPresent(new ByteConsumer() {
MrHadiSatrio/Optional
src/test/java/com/hadisatrio/optional/OptionalByteTest.java
// Path: src/main/java/com/hadisatrio/optional/function/ByteConsumer.java // public interface ByteConsumer { // // void consume(byte value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ByteSupplier.java // public interface ByteSupplier { // // byte get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // }
import com.hadisatrio.optional.function.ByteConsumer; import com.hadisatrio.optional.function.ByteSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test;
Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void ifPresent() throws Exception { OptionalByte.of(((byte) 42)).ifPresent(new ByteConsumer() { @Override public void consume(byte value) { Assert.assertEquals(((byte) 42), value); } }); OptionalByte.absent().ifPresent(new ByteConsumer() { @Override public void consume(byte value) { Assert.fail("ifPresent() on an absent optional should never call its consumer"); } }); } @Test public void ifPresentOrElse() throws Exception { OptionalByte.of(((byte) 42)).ifPresentOrElse(new ByteConsumer() { @Override public void consume(byte value) { Assert.assertEquals(((byte) 42), value); }
// Path: src/main/java/com/hadisatrio/optional/function/ByteConsumer.java // public interface ByteConsumer { // // void consume(byte value); // } // // Path: src/main/java/com/hadisatrio/optional/function/ByteSupplier.java // public interface ByteSupplier { // // byte get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // } // Path: src/test/java/com/hadisatrio/optional/OptionalByteTest.java import com.hadisatrio.optional.function.ByteConsumer; import com.hadisatrio.optional.function.ByteSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import org.junit.Assert; import org.junit.Test; Assert.fail("Invoking orThrow() on an absent optional should throw an exception."); } catch (Exception anException) { // No-op. This is the expected behaviour. } } @Test public void ifPresent() throws Exception { OptionalByte.of(((byte) 42)).ifPresent(new ByteConsumer() { @Override public void consume(byte value) { Assert.assertEquals(((byte) 42), value); } }); OptionalByte.absent().ifPresent(new ByteConsumer() { @Override public void consume(byte value) { Assert.fail("ifPresent() on an absent optional should never call its consumer"); } }); } @Test public void ifPresentOrElse() throws Exception { OptionalByte.of(((byte) 42)).ifPresentOrElse(new ByteConsumer() { @Override public void consume(byte value) { Assert.assertEquals(((byte) 42), value); }
}, new Function() {
MrHadiSatrio/Optional
src/main/java/com/hadisatrio/optional/OptionalChar.java
// Path: src/main/java/com/hadisatrio/optional/function/CharConsumer.java // public interface CharConsumer { // // void consume(char value); // } // // Path: src/main/java/com/hadisatrio/optional/function/CharSupplier.java // public interface CharSupplier { // // char get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // }
import com.hadisatrio.optional.function.CharConsumer; import com.hadisatrio.optional.function.CharSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import java.io.Serializable;
* * @return the value held by this {@code OptionalChar} * @throws IllegalStateException if there is no value present */ public char get() { if (isPresent()) { return value; } throw new IllegalStateException("Value is absent."); } /** * Return the value if present, otherwise return {@code other}. * * @param other the value to be returned if there is no value present * @return the value, if present, otherwise {@code other} */ public char or(char other) { return isPresent() ? value : other; } /** * Return the value if present, otherwise invoke {@code otherSupplier} and return * the result of that invocation. * * @param otherSupplier a {@code Supplier} whose result is returned if no value * is present * @return the value if present otherwise the result of {@code otherSupplier.get()} * @throws IllegalArgumentException if {@code otherSupplier} is null */
// Path: src/main/java/com/hadisatrio/optional/function/CharConsumer.java // public interface CharConsumer { // // void consume(char value); // } // // Path: src/main/java/com/hadisatrio/optional/function/CharSupplier.java // public interface CharSupplier { // // char get(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Function.java // public interface Function { // // void call(); // } // // Path: src/main/java/com/hadisatrio/optional/function/Supplier.java // public interface Supplier<T> { // // T get(); // } // Path: src/main/java/com/hadisatrio/optional/OptionalChar.java import com.hadisatrio.optional.function.CharConsumer; import com.hadisatrio.optional.function.CharSupplier; import com.hadisatrio.optional.function.Function; import com.hadisatrio.optional.function.Supplier; import java.io.Serializable; * * @return the value held by this {@code OptionalChar} * @throws IllegalStateException if there is no value present */ public char get() { if (isPresent()) { return value; } throw new IllegalStateException("Value is absent."); } /** * Return the value if present, otherwise return {@code other}. * * @param other the value to be returned if there is no value present * @return the value, if present, otherwise {@code other} */ public char or(char other) { return isPresent() ? value : other; } /** * Return the value if present, otherwise invoke {@code otherSupplier} and return * the result of that invocation. * * @param otherSupplier a {@code Supplier} whose result is returned if no value * is present * @return the value if present otherwise the result of {@code otherSupplier.get()} * @throws IllegalArgumentException if {@code otherSupplier} is null */
public char or(CharSupplier otherSupplier) {