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 |
|---|---|---|---|---|---|---|
emmaguy/wear-notify-for-reddit | mobile/src/main/java/com/emmaguy/todayilearned/refresh/BasicAuthorisationRequestInterceptorBuilder.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
| import com.emmaguy.todayilearned.settings.Encoder;
import com.emmaguy.todayilearned.sharedlib.Constants;
import retrofit.RequestInterceptor; | package com.emmaguy.todayilearned.refresh;
/**
* Created by emma on 14/06/15.
*/
public class BasicAuthorisationRequestInterceptorBuilder {
private Encoder mEncoder;
public BasicAuthorisationRequestInterceptorBuilder(Encoder encoder) {
mEncoder = encoder;
}
public RequestInterceptor build(final String credentials) {
return new RequestInterceptor() {
@Override public void intercept(RequestInterceptor.RequestFacade request) { | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
// Path: mobile/src/main/java/com/emmaguy/todayilearned/refresh/BasicAuthorisationRequestInterceptorBuilder.java
import com.emmaguy.todayilearned.settings.Encoder;
import com.emmaguy.todayilearned.sharedlib.Constants;
import retrofit.RequestInterceptor;
package com.emmaguy.todayilearned.refresh;
/**
* Created by emma on 14/06/15.
*/
public class BasicAuthorisationRequestInterceptorBuilder {
private Encoder mEncoder;
public BasicAuthorisationRequestInterceptorBuilder(Encoder encoder) {
mEncoder = encoder;
}
public RequestInterceptor build(final String credentials) {
return new RequestInterceptor() {
@Override public void intercept(RequestInterceptor.RequestFacade request) { | request.addHeader(Constants.AUTHORIZATION, |
emmaguy/wear-notify-for-reddit | mobile/src/main/java/com/emmaguy/todayilearned/refresh/BackgroundAlarmListener.java | // Path: mobile/src/main/java/com/emmaguy/todayilearned/App.java
// public class App extends Application {
// private final boolean mIsDebug = BuildConfig.DEBUG;
//
// private AppComponent mAppComponent;
//
// public static App with(Context context) {
// return (App) context.getApplicationContext();
// }
//
// @Override public void onCreate() {
// super.onCreate();
//
// mAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
// mAppComponent.inject(this);
//
// if (mIsDebug) {
// Timber.plant(new Timber.DebugTree());
// } else {
// Timber.plant(new FirebaseTree());
// }
// }
//
// public AppComponent getAppComponent() {
// return mAppComponent;
// }
//
// public boolean isDebug() {
// return mIsDebug;
// }
// }
//
// Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
| import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import com.emmaguy.todayilearned.App;
import com.emmaguy.todayilearned.storage.UserStorage;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject; | package com.emmaguy.todayilearned.refresh;
public class BackgroundAlarmListener implements WakefulIntentService.AlarmListener {
@Inject UserStorage mUserStorage;
public void scheduleAlarms(AlarmManager mgr, PendingIntent pi, Context context) { | // Path: mobile/src/main/java/com/emmaguy/todayilearned/App.java
// public class App extends Application {
// private final boolean mIsDebug = BuildConfig.DEBUG;
//
// private AppComponent mAppComponent;
//
// public static App with(Context context) {
// return (App) context.getApplicationContext();
// }
//
// @Override public void onCreate() {
// super.onCreate();
//
// mAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
// mAppComponent.inject(this);
//
// if (mIsDebug) {
// Timber.plant(new Timber.DebugTree());
// } else {
// Timber.plant(new FirebaseTree());
// }
// }
//
// public AppComponent getAppComponent() {
// return mAppComponent;
// }
//
// public boolean isDebug() {
// return mIsDebug;
// }
// }
//
// Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
// Path: mobile/src/main/java/com/emmaguy/todayilearned/refresh/BackgroundAlarmListener.java
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import com.emmaguy.todayilearned.App;
import com.emmaguy.todayilearned.storage.UserStorage;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
package com.emmaguy.todayilearned.refresh;
public class BackgroundAlarmListener implements WakefulIntentService.AlarmListener {
@Inject UserStorage mUserStorage;
public void scheduleAlarms(AlarmManager mgr, PendingIntent pi, Context context) { | App.with(context).getAppComponent().inject(this); |
emmaguy/wear-notify-for-reddit | mobile/src/main/java/com/emmaguy/todayilearned/refresh/PostConverter.java | // Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
| import android.content.res.Resources;
import com.emmaguy.todayilearned.storage.UserStorage;
import java.lang.reflect.Type;
import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
import retrofit.converter.GsonConverter;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput; | package com.emmaguy.todayilearned.refresh;
public class PostConverter implements Converter {
private final GsonConverter mOriginalConverter; | // Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
// Path: mobile/src/main/java/com/emmaguy/todayilearned/refresh/PostConverter.java
import android.content.res.Resources;
import com.emmaguy.todayilearned.storage.UserStorage;
import java.lang.reflect.Type;
import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
import retrofit.converter.GsonConverter;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput;
package com.emmaguy.todayilearned.refresh;
public class PostConverter implements Converter {
private final GsonConverter mOriginalConverter; | private final UserStorage mUserStorage; |
emmaguy/wear-notify-for-reddit | mobile/src/main/java/com/emmaguy/todayilearned/Analytics.java | // Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
| import android.os.Bundle;
import com.emmaguy.todayilearned.storage.TokenStorage;
import com.emmaguy.todayilearned.storage.UserStorage;
import com.google.firebase.analytics.FirebaseAnalytics;
import timber.log.Timber; | package com.emmaguy.todayilearned;
public class Analytics {
private final FirebaseAnalytics mFirebaseAnalytics;
public Analytics(FirebaseAnalytics firebaseAnalytics) {
this.mFirebaseAnalytics = firebaseAnalytics;
mFirebaseAnalytics.setUserProperty("build_time", BuildConfig.BUILD_TIME);
mFirebaseAnalytics.setUserProperty("git_sha", BuildConfig.GIT_SHA);
}
public void sendLogin(boolean loginSuccessful) {
Timber.d("Sending event login successful: %s", loginSuccessful);
Bundle bundle = new Bundle();
bundle.putBoolean("login_success", loginSuccessful);
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.LOGIN, bundle);
}
public void sendEvent(String category, String result) {
Timber.d("Sending event: %s , %s", category, result);
Bundle bundle = new Bundle();
bundle.putString("name", result);
mFirebaseAnalytics.logEvent(category, bundle);
}
| // Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
// Path: mobile/src/main/java/com/emmaguy/todayilearned/Analytics.java
import android.os.Bundle;
import com.emmaguy.todayilearned.storage.TokenStorage;
import com.emmaguy.todayilearned.storage.UserStorage;
import com.google.firebase.analytics.FirebaseAnalytics;
import timber.log.Timber;
package com.emmaguy.todayilearned;
public class Analytics {
private final FirebaseAnalytics mFirebaseAnalytics;
public Analytics(FirebaseAnalytics firebaseAnalytics) {
this.mFirebaseAnalytics = firebaseAnalytics;
mFirebaseAnalytics.setUserProperty("build_time", BuildConfig.BUILD_TIME);
mFirebaseAnalytics.setUserProperty("git_sha", BuildConfig.GIT_SHA);
}
public void sendLogin(boolean loginSuccessful) {
Timber.d("Sending event login successful: %s", loginSuccessful);
Bundle bundle = new Bundle();
bundle.putBoolean("login_success", loginSuccessful);
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.LOGIN, bundle);
}
public void sendEvent(String category, String result) {
Timber.d("Sending event: %s , %s", category, result);
Bundle bundle = new Bundle();
bundle.putString("name", result);
mFirebaseAnalytics.logEvent(category, bundle);
}
| public void sendRefreshEvent(UserStorage userStorage, TokenStorage tokenStorage) { |
matyb/java-koans | lib/src/test/java/com/sandwich/util/KoanComparatorTest.java | // Path: lib/src/main/java/com/sandwich/koan/KoanMethod.java
// public class KoanMethod {
//
// private final transient Method method;
// private final String lesson;
// private final boolean displayIncompleteException;
// private static final KoanSuiteCompilationListener listener = new KoanSuiteCompilationListener();
//
// private KoanMethod(KoanElementAttributes koanAttributes) throws SecurityException, NoSuchMethodException{
// this(null, koanAttributes);
// }
//
// public static KoanMethod getInstance(KoanElementAttributes koanAttributes){
// try {
// return new KoanMethod(koanAttributes);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public static KoanMethod getInstance(Method method){
// return new KoanMethod(null, method, true);
// }
//
// public static KoanMethod getInstance(String lesson, Method method){
// return new KoanMethod(lesson, method, true);
// }
//
// private KoanMethod(String lesson, Method method, boolean displayIncompleteException){
// if(method == null){
// throw new IllegalArgumentException("method may not be null");
// }
// this.method = method;
// this.lesson = new RbVariableInjector(lesson, method).injectLessonVariables();
// this.displayIncompleteException = displayIncompleteException;
// }
//
// public KoanMethod(String lesson, KoanElementAttributes koanAttributes) throws SecurityException, NoSuchMethodException {
// this( lesson,
// KoanClassLoader.getInstance().loadClass(koanAttributes.className, listener)
// .getMethod(koanAttributes.name),
// !"false".equalsIgnoreCase(koanAttributes.displayIncompleteKoanException));
// }
//
// public String getLesson() {
// return lesson;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public boolean displayIncompleteException() {
// return displayIncompleteException;
// }
//
// public KoanMethod clone(Method method){
// return new KoanMethod(lesson, method, displayIncompleteException);
// }
//
// @Override public String toString(){
// return "{"+getMethod().getName()
// +" : "+ (lesson.length() > 20 ? lesson.substring(0, 20) + "..." : lesson)+"}";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (displayIncompleteException ? 1231 : 1237);
// result = prime * result + ((lesson == null) ? 0 : lesson.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// KoanMethod other = (KoanMethod) obj;
// if (displayIncompleteException != other.displayIncompleteException)
// return false;
// if (lesson == null) {
// if (other.lesson != null)
// return false;
// } else if (!lesson.equals(other.lesson))
// return false;
// return true;
// }
//
//
// }
| import static org.junit.Assert.assertSame;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import com.sandwich.koan.Koan;
import com.sandwich.koan.KoanMethod;
import com.sandwich.koan.path.CommandLineTestCase; | package com.sandwich.util;
public class KoanComparatorTest extends CommandLineTestCase {
interface Caps {
public String capitalize(String name);
}
@Test
public void testThatKomparatorBombsWhenNotFound() throws Exception {
Method m = new Object(){
@Koan public void someMethod(){}
}.getClass().getDeclaredMethod("someMethod");
KoanComparator comparator = new KoanComparator();
try{ | // Path: lib/src/main/java/com/sandwich/koan/KoanMethod.java
// public class KoanMethod {
//
// private final transient Method method;
// private final String lesson;
// private final boolean displayIncompleteException;
// private static final KoanSuiteCompilationListener listener = new KoanSuiteCompilationListener();
//
// private KoanMethod(KoanElementAttributes koanAttributes) throws SecurityException, NoSuchMethodException{
// this(null, koanAttributes);
// }
//
// public static KoanMethod getInstance(KoanElementAttributes koanAttributes){
// try {
// return new KoanMethod(koanAttributes);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public static KoanMethod getInstance(Method method){
// return new KoanMethod(null, method, true);
// }
//
// public static KoanMethod getInstance(String lesson, Method method){
// return new KoanMethod(lesson, method, true);
// }
//
// private KoanMethod(String lesson, Method method, boolean displayIncompleteException){
// if(method == null){
// throw new IllegalArgumentException("method may not be null");
// }
// this.method = method;
// this.lesson = new RbVariableInjector(lesson, method).injectLessonVariables();
// this.displayIncompleteException = displayIncompleteException;
// }
//
// public KoanMethod(String lesson, KoanElementAttributes koanAttributes) throws SecurityException, NoSuchMethodException {
// this( lesson,
// KoanClassLoader.getInstance().loadClass(koanAttributes.className, listener)
// .getMethod(koanAttributes.name),
// !"false".equalsIgnoreCase(koanAttributes.displayIncompleteKoanException));
// }
//
// public String getLesson() {
// return lesson;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public boolean displayIncompleteException() {
// return displayIncompleteException;
// }
//
// public KoanMethod clone(Method method){
// return new KoanMethod(lesson, method, displayIncompleteException);
// }
//
// @Override public String toString(){
// return "{"+getMethod().getName()
// +" : "+ (lesson.length() > 20 ? lesson.substring(0, 20) + "..." : lesson)+"}";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (displayIncompleteException ? 1231 : 1237);
// result = prime * result + ((lesson == null) ? 0 : lesson.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// KoanMethod other = (KoanMethod) obj;
// if (displayIncompleteException != other.displayIncompleteException)
// return false;
// if (lesson == null) {
// if (other.lesson != null)
// return false;
// } else if (!lesson.equals(other.lesson))
// return false;
// return true;
// }
//
//
// }
// Path: lib/src/test/java/com/sandwich/util/KoanComparatorTest.java
import static org.junit.Assert.assertSame;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import com.sandwich.koan.Koan;
import com.sandwich.koan.KoanMethod;
import com.sandwich.koan.path.CommandLineTestCase;
package com.sandwich.util;
public class KoanComparatorTest extends CommandLineTestCase {
interface Caps {
public String capitalize(String name);
}
@Test
public void testThatKomparatorBombsWhenNotFound() throws Exception {
Method m = new Object(){
@Koan public void someMethod(){}
}.getClass().getDeclaredMethod("someMethod");
KoanComparator comparator = new KoanComparator();
try{ | comparator.compare(KoanMethod.getInstance("2",m), KoanMethod.getInstance("1",m)); |
matyb/java-koans | koans/src/beginner/AboutAssertions.java | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
| import com.sandwich.koan.Koan;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.*; | package beginner;
public class AboutAssertions {
@Koan
public void assertBooleanTrue() {
// there are two possibilities, true or false, what would it be here? | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
// Path: koans/src/beginner/AboutAssertions.java
import com.sandwich.koan.Koan;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.*;
package beginner;
public class AboutAssertions {
@Koan
public void assertBooleanTrue() {
// there are two possibilities, true or false, what would it be here? | assertTrue(__); |
matyb/java-koans | koans/src/intermediate/AboutFileIO.java | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
| import com.sandwich.koan.Koan;
import java.io.*;
import java.util.logging.Logger;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals; | package intermediate;
public class AboutFileIO {
@Koan
public void fileObjectDoesntCreateFile() {
File f = new File("i-never.exist"); | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
// Path: koans/src/intermediate/AboutFileIO.java
import com.sandwich.koan.Koan;
import java.io.*;
import java.util.logging.Logger;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals;
package intermediate;
public class AboutFileIO {
@Koan
public void fileObjectDoesntCreateFile() {
File f = new File("i-never.exist"); | assertEquals(f.exists(), __); |
matyb/java-koans | lib/src/test/java/com/sandwich/koan/suite/BlowUpOnLineEleven.java | // Path: lib/src/main/java/com/sandwich/koan/KoanIncompleteException.java
// public class KoanIncompleteException extends AssertionError {
//
// private static final long serialVersionUID = -4207677767865451508L;
//
// public KoanIncompleteException(String message){
// super(message);
// }
//
// @Override public String toString(){
// return super.getMessage();
// }
//
// }
| import com.sandwich.koan.Koan;
import com.sandwich.koan.KoanIncompleteException; | package com.sandwich.koan.suite;
public class BlowUpOnLineEleven {
// gotta put it on line 11 thus the two lines here
//
@Koan
public void blowUpOnLineEleven() { | // Path: lib/src/main/java/com/sandwich/koan/KoanIncompleteException.java
// public class KoanIncompleteException extends AssertionError {
//
// private static final long serialVersionUID = -4207677767865451508L;
//
// public KoanIncompleteException(String message){
// super(message);
// }
//
// @Override public String toString(){
// return super.getMessage();
// }
//
// }
// Path: lib/src/test/java/com/sandwich/koan/suite/BlowUpOnLineEleven.java
import com.sandwich.koan.Koan;
import com.sandwich.koan.KoanIncompleteException;
package com.sandwich.koan.suite;
public class BlowUpOnLineEleven {
// gotta put it on line 11 thus the two lines here
//
@Koan
public void blowUpOnLineEleven() { | throw new KoanIncompleteException(null); |
matyb/java-koans | lib/src/main/java/com/sandwich/koan/KoanMethod.java | // Path: lib/src/main/java/com/sandwich/koan/path/xmltransformation/KoanElementAttributes.java
// public class KoanElementAttributes{
//
// public String name, displayIncompleteKoanException, className;
//
// public KoanElementAttributes(String name, String displayIncompleteKoanException, String className){
// this.name = name;
// this.displayIncompleteKoanException = displayIncompleteKoanException;
// this.className = className;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result
// + ((className == null) ? 0 : className.hashCode());
// result = prime
// * result
// + ((displayIncompleteKoanException == null) ? 0
// : displayIncompleteKoanException.hashCode());
// result = prime * result + ((name == null) ? 0 : name.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// KoanElementAttributes other = (KoanElementAttributes) obj;
// if (className == null) {
// if (other.className != null)
// return false;
// } else if (!className.equals(other.className))
// return false;
// if (displayIncompleteKoanException == null) {
// if (other.displayIncompleteKoanException != null)
// return false;
// } else if (!displayIncompleteKoanException
// .equals(other.displayIncompleteKoanException))
// return false;
// if (name == null) {
// if (other.name != null)
// return false;
// } else if (!name.equals(other.name))
// return false;
// return true;
// }
//
// @Override
// public String toString() {
// return "KoanElementAttributes [name=" + name
// + ", displayIncompleteKoanException="
// + displayIncompleteKoanException + ", className=" + className
// + "]";
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/koan/path/xmltransformation/RbVariableInjector.java
// public class RbVariableInjector {
//
// private final String lesson;
// private final String methodName;
// private final String suiteName;
// private final String suitePath;
//
//
// public RbVariableInjector(String lesson, Method koanMethod){
// if(koanMethod == null){
// throw new IllegalArgumentException("koanMethod may not be null");
// }
// Class<?> declaringClass = koanMethod.getDeclaringClass();
// if(lesson == null){
// lesson = Strings.getMessage(declaringClass.getCanonicalName() + '.' + koanMethod.getName());
// if(Strings.wasNotFound(lesson)){
// lesson = null;
// }
// }
// this.lesson = lesson;
// methodName = koanMethod.getName();
// suiteName = declaringClass.getSimpleName();
// String path = FileCompiler.getSourceFileFromClass(DirectoryManager.getSourceDir(), declaringClass.getName()).getAbsolutePath();
// suitePath = path.substring(0, path.lastIndexOf(DirectoryManager.FILESYSTEM_SEPARATOR) + 1);
// }
//
// public String injectLessonVariables() {
// if(lesson == null || lesson.length() == 0 ||
// lesson.indexOf(KoanConstants.XML_PARAMETER_START) < 0){
// return lesson;
// }
// StringBuffer sb = new StringBuffer(lesson);
// replace(sb, XmlVariableDictionary.FILE_NAME, suiteName);
// replace(sb, XmlVariableDictionary.FILE_PATH, suitePath);
// replace(sb, XmlVariableDictionary.METHOD_NAME, methodName);
// return sb.toString();
// }
//
// private void replace(StringBuffer sb, String keyword, String value) {
// int indexOfKeyword = sb.indexOf(keyword);
// if(indexOfKeyword < 0){
// return;
// }
// sb.replace(indexOfKeyword, indexOfKeyword+keyword.length(), value);
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/util/io/KoanSuiteCompilationListener.java
// public class KoanSuiteCompilationListener implements CompilationListener {
//
// private boolean lastCompilationAttemptFailed = false;
// private String lastMessageShown = null;
//
// public void compilationFailed(File src, String[] command, int exitCode, String errorMessage, Throwable x) {
// if(lastMessageShown == null || !errorMessage.trim().equals(lastMessageShown.trim())){
// FileCompilerAction.LOGGING_HANDLER.compilationFailed(src, command, exitCode, errorMessage, x);
// }
// lastMessageShown = errorMessage;
// lastCompilationAttemptFailed = true;
// }
//
// public void compilationSucceeded(File src, String[] command, String stdIo, Throwable x) {
// lastMessageShown = null; // reset last failed compilation message
// lastCompilationAttemptFailed = false;
// }
//
// public boolean isLastCompilationAttemptFailure(){
// return lastCompilationAttemptFailed;
// }
// }
| import java.lang.reflect.Method;
import com.sandwich.koan.path.xmltransformation.KoanElementAttributes;
import com.sandwich.koan.path.xmltransformation.RbVariableInjector;
import com.sandwich.util.io.KoanSuiteCompilationListener; | package com.sandwich.koan;
public class KoanMethod {
private final transient Method method;
private final String lesson;
private final boolean displayIncompleteException; | // Path: lib/src/main/java/com/sandwich/koan/path/xmltransformation/KoanElementAttributes.java
// public class KoanElementAttributes{
//
// public String name, displayIncompleteKoanException, className;
//
// public KoanElementAttributes(String name, String displayIncompleteKoanException, String className){
// this.name = name;
// this.displayIncompleteKoanException = displayIncompleteKoanException;
// this.className = className;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result
// + ((className == null) ? 0 : className.hashCode());
// result = prime
// * result
// + ((displayIncompleteKoanException == null) ? 0
// : displayIncompleteKoanException.hashCode());
// result = prime * result + ((name == null) ? 0 : name.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// KoanElementAttributes other = (KoanElementAttributes) obj;
// if (className == null) {
// if (other.className != null)
// return false;
// } else if (!className.equals(other.className))
// return false;
// if (displayIncompleteKoanException == null) {
// if (other.displayIncompleteKoanException != null)
// return false;
// } else if (!displayIncompleteKoanException
// .equals(other.displayIncompleteKoanException))
// return false;
// if (name == null) {
// if (other.name != null)
// return false;
// } else if (!name.equals(other.name))
// return false;
// return true;
// }
//
// @Override
// public String toString() {
// return "KoanElementAttributes [name=" + name
// + ", displayIncompleteKoanException="
// + displayIncompleteKoanException + ", className=" + className
// + "]";
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/koan/path/xmltransformation/RbVariableInjector.java
// public class RbVariableInjector {
//
// private final String lesson;
// private final String methodName;
// private final String suiteName;
// private final String suitePath;
//
//
// public RbVariableInjector(String lesson, Method koanMethod){
// if(koanMethod == null){
// throw new IllegalArgumentException("koanMethod may not be null");
// }
// Class<?> declaringClass = koanMethod.getDeclaringClass();
// if(lesson == null){
// lesson = Strings.getMessage(declaringClass.getCanonicalName() + '.' + koanMethod.getName());
// if(Strings.wasNotFound(lesson)){
// lesson = null;
// }
// }
// this.lesson = lesson;
// methodName = koanMethod.getName();
// suiteName = declaringClass.getSimpleName();
// String path = FileCompiler.getSourceFileFromClass(DirectoryManager.getSourceDir(), declaringClass.getName()).getAbsolutePath();
// suitePath = path.substring(0, path.lastIndexOf(DirectoryManager.FILESYSTEM_SEPARATOR) + 1);
// }
//
// public String injectLessonVariables() {
// if(lesson == null || lesson.length() == 0 ||
// lesson.indexOf(KoanConstants.XML_PARAMETER_START) < 0){
// return lesson;
// }
// StringBuffer sb = new StringBuffer(lesson);
// replace(sb, XmlVariableDictionary.FILE_NAME, suiteName);
// replace(sb, XmlVariableDictionary.FILE_PATH, suitePath);
// replace(sb, XmlVariableDictionary.METHOD_NAME, methodName);
// return sb.toString();
// }
//
// private void replace(StringBuffer sb, String keyword, String value) {
// int indexOfKeyword = sb.indexOf(keyword);
// if(indexOfKeyword < 0){
// return;
// }
// sb.replace(indexOfKeyword, indexOfKeyword+keyword.length(), value);
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/util/io/KoanSuiteCompilationListener.java
// public class KoanSuiteCompilationListener implements CompilationListener {
//
// private boolean lastCompilationAttemptFailed = false;
// private String lastMessageShown = null;
//
// public void compilationFailed(File src, String[] command, int exitCode, String errorMessage, Throwable x) {
// if(lastMessageShown == null || !errorMessage.trim().equals(lastMessageShown.trim())){
// FileCompilerAction.LOGGING_HANDLER.compilationFailed(src, command, exitCode, errorMessage, x);
// }
// lastMessageShown = errorMessage;
// lastCompilationAttemptFailed = true;
// }
//
// public void compilationSucceeded(File src, String[] command, String stdIo, Throwable x) {
// lastMessageShown = null; // reset last failed compilation message
// lastCompilationAttemptFailed = false;
// }
//
// public boolean isLastCompilationAttemptFailure(){
// return lastCompilationAttemptFailed;
// }
// }
// Path: lib/src/main/java/com/sandwich/koan/KoanMethod.java
import java.lang.reflect.Method;
import com.sandwich.koan.path.xmltransformation.KoanElementAttributes;
import com.sandwich.koan.path.xmltransformation.RbVariableInjector;
import com.sandwich.util.io.KoanSuiteCompilationListener;
package com.sandwich.koan;
public class KoanMethod {
private final transient Method method;
private final String lesson;
private final boolean displayIncompleteException; | private static final KoanSuiteCompilationListener listener = new KoanSuiteCompilationListener(); |
matyb/java-koans | lib/src/main/java/com/sandwich/koan/KoanMethod.java | // Path: lib/src/main/java/com/sandwich/koan/path/xmltransformation/KoanElementAttributes.java
// public class KoanElementAttributes{
//
// public String name, displayIncompleteKoanException, className;
//
// public KoanElementAttributes(String name, String displayIncompleteKoanException, String className){
// this.name = name;
// this.displayIncompleteKoanException = displayIncompleteKoanException;
// this.className = className;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result
// + ((className == null) ? 0 : className.hashCode());
// result = prime
// * result
// + ((displayIncompleteKoanException == null) ? 0
// : displayIncompleteKoanException.hashCode());
// result = prime * result + ((name == null) ? 0 : name.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// KoanElementAttributes other = (KoanElementAttributes) obj;
// if (className == null) {
// if (other.className != null)
// return false;
// } else if (!className.equals(other.className))
// return false;
// if (displayIncompleteKoanException == null) {
// if (other.displayIncompleteKoanException != null)
// return false;
// } else if (!displayIncompleteKoanException
// .equals(other.displayIncompleteKoanException))
// return false;
// if (name == null) {
// if (other.name != null)
// return false;
// } else if (!name.equals(other.name))
// return false;
// return true;
// }
//
// @Override
// public String toString() {
// return "KoanElementAttributes [name=" + name
// + ", displayIncompleteKoanException="
// + displayIncompleteKoanException + ", className=" + className
// + "]";
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/koan/path/xmltransformation/RbVariableInjector.java
// public class RbVariableInjector {
//
// private final String lesson;
// private final String methodName;
// private final String suiteName;
// private final String suitePath;
//
//
// public RbVariableInjector(String lesson, Method koanMethod){
// if(koanMethod == null){
// throw new IllegalArgumentException("koanMethod may not be null");
// }
// Class<?> declaringClass = koanMethod.getDeclaringClass();
// if(lesson == null){
// lesson = Strings.getMessage(declaringClass.getCanonicalName() + '.' + koanMethod.getName());
// if(Strings.wasNotFound(lesson)){
// lesson = null;
// }
// }
// this.lesson = lesson;
// methodName = koanMethod.getName();
// suiteName = declaringClass.getSimpleName();
// String path = FileCompiler.getSourceFileFromClass(DirectoryManager.getSourceDir(), declaringClass.getName()).getAbsolutePath();
// suitePath = path.substring(0, path.lastIndexOf(DirectoryManager.FILESYSTEM_SEPARATOR) + 1);
// }
//
// public String injectLessonVariables() {
// if(lesson == null || lesson.length() == 0 ||
// lesson.indexOf(KoanConstants.XML_PARAMETER_START) < 0){
// return lesson;
// }
// StringBuffer sb = new StringBuffer(lesson);
// replace(sb, XmlVariableDictionary.FILE_NAME, suiteName);
// replace(sb, XmlVariableDictionary.FILE_PATH, suitePath);
// replace(sb, XmlVariableDictionary.METHOD_NAME, methodName);
// return sb.toString();
// }
//
// private void replace(StringBuffer sb, String keyword, String value) {
// int indexOfKeyword = sb.indexOf(keyword);
// if(indexOfKeyword < 0){
// return;
// }
// sb.replace(indexOfKeyword, indexOfKeyword+keyword.length(), value);
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/util/io/KoanSuiteCompilationListener.java
// public class KoanSuiteCompilationListener implements CompilationListener {
//
// private boolean lastCompilationAttemptFailed = false;
// private String lastMessageShown = null;
//
// public void compilationFailed(File src, String[] command, int exitCode, String errorMessage, Throwable x) {
// if(lastMessageShown == null || !errorMessage.trim().equals(lastMessageShown.trim())){
// FileCompilerAction.LOGGING_HANDLER.compilationFailed(src, command, exitCode, errorMessage, x);
// }
// lastMessageShown = errorMessage;
// lastCompilationAttemptFailed = true;
// }
//
// public void compilationSucceeded(File src, String[] command, String stdIo, Throwable x) {
// lastMessageShown = null; // reset last failed compilation message
// lastCompilationAttemptFailed = false;
// }
//
// public boolean isLastCompilationAttemptFailure(){
// return lastCompilationAttemptFailed;
// }
// }
| import java.lang.reflect.Method;
import com.sandwich.koan.path.xmltransformation.KoanElementAttributes;
import com.sandwich.koan.path.xmltransformation.RbVariableInjector;
import com.sandwich.util.io.KoanSuiteCompilationListener; | package com.sandwich.koan;
public class KoanMethod {
private final transient Method method;
private final String lesson;
private final boolean displayIncompleteException;
private static final KoanSuiteCompilationListener listener = new KoanSuiteCompilationListener();
| // Path: lib/src/main/java/com/sandwich/koan/path/xmltransformation/KoanElementAttributes.java
// public class KoanElementAttributes{
//
// public String name, displayIncompleteKoanException, className;
//
// public KoanElementAttributes(String name, String displayIncompleteKoanException, String className){
// this.name = name;
// this.displayIncompleteKoanException = displayIncompleteKoanException;
// this.className = className;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result
// + ((className == null) ? 0 : className.hashCode());
// result = prime
// * result
// + ((displayIncompleteKoanException == null) ? 0
// : displayIncompleteKoanException.hashCode());
// result = prime * result + ((name == null) ? 0 : name.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// KoanElementAttributes other = (KoanElementAttributes) obj;
// if (className == null) {
// if (other.className != null)
// return false;
// } else if (!className.equals(other.className))
// return false;
// if (displayIncompleteKoanException == null) {
// if (other.displayIncompleteKoanException != null)
// return false;
// } else if (!displayIncompleteKoanException
// .equals(other.displayIncompleteKoanException))
// return false;
// if (name == null) {
// if (other.name != null)
// return false;
// } else if (!name.equals(other.name))
// return false;
// return true;
// }
//
// @Override
// public String toString() {
// return "KoanElementAttributes [name=" + name
// + ", displayIncompleteKoanException="
// + displayIncompleteKoanException + ", className=" + className
// + "]";
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/koan/path/xmltransformation/RbVariableInjector.java
// public class RbVariableInjector {
//
// private final String lesson;
// private final String methodName;
// private final String suiteName;
// private final String suitePath;
//
//
// public RbVariableInjector(String lesson, Method koanMethod){
// if(koanMethod == null){
// throw new IllegalArgumentException("koanMethod may not be null");
// }
// Class<?> declaringClass = koanMethod.getDeclaringClass();
// if(lesson == null){
// lesson = Strings.getMessage(declaringClass.getCanonicalName() + '.' + koanMethod.getName());
// if(Strings.wasNotFound(lesson)){
// lesson = null;
// }
// }
// this.lesson = lesson;
// methodName = koanMethod.getName();
// suiteName = declaringClass.getSimpleName();
// String path = FileCompiler.getSourceFileFromClass(DirectoryManager.getSourceDir(), declaringClass.getName()).getAbsolutePath();
// suitePath = path.substring(0, path.lastIndexOf(DirectoryManager.FILESYSTEM_SEPARATOR) + 1);
// }
//
// public String injectLessonVariables() {
// if(lesson == null || lesson.length() == 0 ||
// lesson.indexOf(KoanConstants.XML_PARAMETER_START) < 0){
// return lesson;
// }
// StringBuffer sb = new StringBuffer(lesson);
// replace(sb, XmlVariableDictionary.FILE_NAME, suiteName);
// replace(sb, XmlVariableDictionary.FILE_PATH, suitePath);
// replace(sb, XmlVariableDictionary.METHOD_NAME, methodName);
// return sb.toString();
// }
//
// private void replace(StringBuffer sb, String keyword, String value) {
// int indexOfKeyword = sb.indexOf(keyword);
// if(indexOfKeyword < 0){
// return;
// }
// sb.replace(indexOfKeyword, indexOfKeyword+keyword.length(), value);
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/util/io/KoanSuiteCompilationListener.java
// public class KoanSuiteCompilationListener implements CompilationListener {
//
// private boolean lastCompilationAttemptFailed = false;
// private String lastMessageShown = null;
//
// public void compilationFailed(File src, String[] command, int exitCode, String errorMessage, Throwable x) {
// if(lastMessageShown == null || !errorMessage.trim().equals(lastMessageShown.trim())){
// FileCompilerAction.LOGGING_HANDLER.compilationFailed(src, command, exitCode, errorMessage, x);
// }
// lastMessageShown = errorMessage;
// lastCompilationAttemptFailed = true;
// }
//
// public void compilationSucceeded(File src, String[] command, String stdIo, Throwable x) {
// lastMessageShown = null; // reset last failed compilation message
// lastCompilationAttemptFailed = false;
// }
//
// public boolean isLastCompilationAttemptFailure(){
// return lastCompilationAttemptFailed;
// }
// }
// Path: lib/src/main/java/com/sandwich/koan/KoanMethod.java
import java.lang.reflect.Method;
import com.sandwich.koan.path.xmltransformation.KoanElementAttributes;
import com.sandwich.koan.path.xmltransformation.RbVariableInjector;
import com.sandwich.util.io.KoanSuiteCompilationListener;
package com.sandwich.koan;
public class KoanMethod {
private final transient Method method;
private final String lesson;
private final boolean displayIncompleteException;
private static final KoanSuiteCompilationListener listener = new KoanSuiteCompilationListener();
| private KoanMethod(KoanElementAttributes koanAttributes) throws SecurityException, NoSuchMethodException{ |
matyb/java-koans | lib/src/main/java/com/sandwich/koan/cmdline/behavior/Debug.java | // Path: lib/src/main/java/com/sandwich/koan/ApplicationSettings.java
// public class ApplicationSettings {
//
// private static ResourceBundle CONFIG_BUNDLE;
//
// private static boolean debug;
//
// public static void setDebug(boolean debug2) {
// debug = debug2;
// }
//
// public static boolean isDebug(){
// return debug || isEqual(getConfigBundle().getString("debug"), true, true);
// }
//
// public static boolean isEncouragementEnabled(){
// return isEqual(getConfigBundle().getString("enable_encouragement"), true, true);
// }
//
// public static boolean isExpectationResultVisible(){
// return isEqual(getConfigBundle().getString("enable_expectation_result"), true, true);
// }
//
// public static boolean isInteractive(){
// return isEqual(getConfigBundle().getString("interactive"), true, true);
// }
//
// public static char getExitChar(){
// return getConfigBundle().getString("exit_character").charAt(0);
// }
//
// public static String getPathXmlFileName(){
// return getConfigBundle().getString("path_xml_filename");
// }
//
// public static long getFileCompilationTimeoutInMs(){
// return Long.valueOf(getConfigBundle().getString("compile_timeout_in_ms"));
// }
//
// public static String getMonitorIgnorePattern(){
// return getConfigBundle().getString("ignore_from_monitoring");
// }
//
// private static boolean isEqual(String value, Object e2, boolean ignoreCase){
// if(value == e2){
// return true;
// }
// if(value != null){
// String stringValue = String.valueOf(e2);
// return ignoreCase ? value.equalsIgnoreCase(stringValue) : value.equals(stringValue);
// }
// return false;
// }
//
// private static ResourceBundle getConfigBundle(){
// if(CONFIG_BUNDLE == null){
// try {
// CONFIG_BUNDLE = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getConfigDir(), "config.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// return CONFIG_BUNDLE;
// }
//
// }
| import com.sandwich.koan.ApplicationSettings; | package com.sandwich.koan.cmdline.behavior;
public class Debug extends AbstractArgumentBehavior{
public void run(String... args){ | // Path: lib/src/main/java/com/sandwich/koan/ApplicationSettings.java
// public class ApplicationSettings {
//
// private static ResourceBundle CONFIG_BUNDLE;
//
// private static boolean debug;
//
// public static void setDebug(boolean debug2) {
// debug = debug2;
// }
//
// public static boolean isDebug(){
// return debug || isEqual(getConfigBundle().getString("debug"), true, true);
// }
//
// public static boolean isEncouragementEnabled(){
// return isEqual(getConfigBundle().getString("enable_encouragement"), true, true);
// }
//
// public static boolean isExpectationResultVisible(){
// return isEqual(getConfigBundle().getString("enable_expectation_result"), true, true);
// }
//
// public static boolean isInteractive(){
// return isEqual(getConfigBundle().getString("interactive"), true, true);
// }
//
// public static char getExitChar(){
// return getConfigBundle().getString("exit_character").charAt(0);
// }
//
// public static String getPathXmlFileName(){
// return getConfigBundle().getString("path_xml_filename");
// }
//
// public static long getFileCompilationTimeoutInMs(){
// return Long.valueOf(getConfigBundle().getString("compile_timeout_in_ms"));
// }
//
// public static String getMonitorIgnorePattern(){
// return getConfigBundle().getString("ignore_from_monitoring");
// }
//
// private static boolean isEqual(String value, Object e2, boolean ignoreCase){
// if(value == e2){
// return true;
// }
// if(value != null){
// String stringValue = String.valueOf(e2);
// return ignoreCase ? value.equalsIgnoreCase(stringValue) : value.equals(stringValue);
// }
// return false;
// }
//
// private static ResourceBundle getConfigBundle(){
// if(CONFIG_BUNDLE == null){
// try {
// CONFIG_BUNDLE = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getConfigDir(), "config.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// return CONFIG_BUNDLE;
// }
//
// }
// Path: lib/src/main/java/com/sandwich/koan/cmdline/behavior/Debug.java
import com.sandwich.koan.ApplicationSettings;
package com.sandwich.koan.cmdline.behavior;
public class Debug extends AbstractArgumentBehavior{
public void run(String... args){ | ApplicationSettings.setDebug(ApplicationSettings.isDebug() || |
matyb/java-koans | lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java | // Path: lib/src/main/java/com/sandwich/util/Strings.java
// public class Strings {
//
// private static final ResourceBundle MESSAGES_BUNDLE = getMessagesBundle();
// private static final String UNFOUND_PROP_VALUE_STRING = "!";
//
// private Strings() {
// }
//
// public static String getMessage(String key) {
// try {
// return MESSAGES_BUNDLE.getString(key);
// } catch (MissingResourceException e) {
// return new StringBuilder(UNFOUND_PROP_VALUE_STRING).append(key).append(UNFOUND_PROP_VALUE_STRING).toString();
// }
// }
//
// public static String getMessage(Class<?> clazz, String key){
// return Strings.getMessage(new StringBuilder(clazz.getSimpleName()).append(PERIOD).append(key).toString());
// }
//
// public static String[] getMessages(Class<?> clazz, String key) {
// String[] tmp = getMessage(clazz, key).split(",");
// String[] trimmed = new String[tmp.length];
// for(int i = 0; i < tmp.length; i++){
// trimmed[i] = tmp[i].trim();
// }
// return trimmed;
// }
//
// private static ResourceBundle getMessagesBundle(){
// if(MESSAGES_BUNDLE == null){
// return createResourceBundle();
// }
// return MESSAGES_BUNDLE;
// }
//
// /**
// * conditionally create messages bundle for proper locale, not on classpath so need to handle manually
// * @return a resource bundle for default locale, or USA if default locale's language has no translated messages
// */
// static ResourceBundle createResourceBundle() {
// ResourceBundle temp = null;
// try {
// temp = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getProjectI18nDir(),
// new StringBuilder("messages_").append(
// Locale.getDefault().getLanguage()).append(
// ".properties").toString())));
// } catch(FileNotFoundException x) {
// try {
// Logger.getLogger(Strings.class.getName()).log(Level.INFO, "Your default language is not supported yet. "+x.getLocalizedMessage());
// temp = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getProjectI18nDir(), "messages_en.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return temp;
// }
//
// public static boolean wasNotFound(String lesson) {
// return lesson.startsWith(UNFOUND_PROP_VALUE_STRING) && lesson.endsWith(UNFOUND_PROP_VALUE_STRING);
// }
// }
| import com.sandwich.util.Strings; | package com.sandwich.koan.constant;
public abstract class KoanConstants {
private KoanConstants(){}
| // Path: lib/src/main/java/com/sandwich/util/Strings.java
// public class Strings {
//
// private static final ResourceBundle MESSAGES_BUNDLE = getMessagesBundle();
// private static final String UNFOUND_PROP_VALUE_STRING = "!";
//
// private Strings() {
// }
//
// public static String getMessage(String key) {
// try {
// return MESSAGES_BUNDLE.getString(key);
// } catch (MissingResourceException e) {
// return new StringBuilder(UNFOUND_PROP_VALUE_STRING).append(key).append(UNFOUND_PROP_VALUE_STRING).toString();
// }
// }
//
// public static String getMessage(Class<?> clazz, String key){
// return Strings.getMessage(new StringBuilder(clazz.getSimpleName()).append(PERIOD).append(key).toString());
// }
//
// public static String[] getMessages(Class<?> clazz, String key) {
// String[] tmp = getMessage(clazz, key).split(",");
// String[] trimmed = new String[tmp.length];
// for(int i = 0; i < tmp.length; i++){
// trimmed[i] = tmp[i].trim();
// }
// return trimmed;
// }
//
// private static ResourceBundle getMessagesBundle(){
// if(MESSAGES_BUNDLE == null){
// return createResourceBundle();
// }
// return MESSAGES_BUNDLE;
// }
//
// /**
// * conditionally create messages bundle for proper locale, not on classpath so need to handle manually
// * @return a resource bundle for default locale, or USA if default locale's language has no translated messages
// */
// static ResourceBundle createResourceBundle() {
// ResourceBundle temp = null;
// try {
// temp = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getProjectI18nDir(),
// new StringBuilder("messages_").append(
// Locale.getDefault().getLanguage()).append(
// ".properties").toString())));
// } catch(FileNotFoundException x) {
// try {
// Logger.getLogger(Strings.class.getName()).log(Level.INFO, "Your default language is not supported yet. "+x.getLocalizedMessage());
// temp = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getProjectI18nDir(), "messages_en.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return temp;
// }
//
// public static boolean wasNotFound(String lesson) {
// return lesson.startsWith(UNFOUND_PROP_VALUE_STRING) && lesson.endsWith(UNFOUND_PROP_VALUE_STRING);
// }
// }
// Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
import com.sandwich.util.Strings;
package com.sandwich.koan.constant;
public abstract class KoanConstants {
private KoanConstants(){}
| public static final String __ = Strings.getMessage("__"); |
matyb/java-koans | lib/src/main/java/com/sandwich/koan/result/KoanMethodResult.java | // Path: lib/src/main/java/com/sandwich/koan/KoanMethod.java
// public class KoanMethod {
//
// private final transient Method method;
// private final String lesson;
// private final boolean displayIncompleteException;
// private static final KoanSuiteCompilationListener listener = new KoanSuiteCompilationListener();
//
// private KoanMethod(KoanElementAttributes koanAttributes) throws SecurityException, NoSuchMethodException{
// this(null, koanAttributes);
// }
//
// public static KoanMethod getInstance(KoanElementAttributes koanAttributes){
// try {
// return new KoanMethod(koanAttributes);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public static KoanMethod getInstance(Method method){
// return new KoanMethod(null, method, true);
// }
//
// public static KoanMethod getInstance(String lesson, Method method){
// return new KoanMethod(lesson, method, true);
// }
//
// private KoanMethod(String lesson, Method method, boolean displayIncompleteException){
// if(method == null){
// throw new IllegalArgumentException("method may not be null");
// }
// this.method = method;
// this.lesson = new RbVariableInjector(lesson, method).injectLessonVariables();
// this.displayIncompleteException = displayIncompleteException;
// }
//
// public KoanMethod(String lesson, KoanElementAttributes koanAttributes) throws SecurityException, NoSuchMethodException {
// this( lesson,
// KoanClassLoader.getInstance().loadClass(koanAttributes.className, listener)
// .getMethod(koanAttributes.name),
// !"false".equalsIgnoreCase(koanAttributes.displayIncompleteKoanException));
// }
//
// public String getLesson() {
// return lesson;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public boolean displayIncompleteException() {
// return displayIncompleteException;
// }
//
// public KoanMethod clone(Method method){
// return new KoanMethod(lesson, method, displayIncompleteException);
// }
//
// @Override public String toString(){
// return "{"+getMethod().getName()
// +" : "+ (lesson.length() > 20 ? lesson.substring(0, 20) + "..." : lesson)+"}";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (displayIncompleteException ? 1231 : 1237);
// result = prime * result + ((lesson == null) ? 0 : lesson.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// KoanMethod other = (KoanMethod) obj;
// if (displayIncompleteException != other.displayIncompleteException)
// return false;
// if (lesson == null) {
// if (other.lesson != null)
// return false;
// } else if (!lesson.equals(other.lesson))
// return false;
// return true;
// }
//
//
// }
| import com.sandwich.koan.KoanMethod; | package com.sandwich.koan.result;
public class KoanMethodResult {
public final static KoanMethodResult PASSED = new KoanMethodResult(null,"PASSED","PASSED");
private final String message;
private final String lineNumber; | // Path: lib/src/main/java/com/sandwich/koan/KoanMethod.java
// public class KoanMethod {
//
// private final transient Method method;
// private final String lesson;
// private final boolean displayIncompleteException;
// private static final KoanSuiteCompilationListener listener = new KoanSuiteCompilationListener();
//
// private KoanMethod(KoanElementAttributes koanAttributes) throws SecurityException, NoSuchMethodException{
// this(null, koanAttributes);
// }
//
// public static KoanMethod getInstance(KoanElementAttributes koanAttributes){
// try {
// return new KoanMethod(koanAttributes);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public static KoanMethod getInstance(Method method){
// return new KoanMethod(null, method, true);
// }
//
// public static KoanMethod getInstance(String lesson, Method method){
// return new KoanMethod(lesson, method, true);
// }
//
// private KoanMethod(String lesson, Method method, boolean displayIncompleteException){
// if(method == null){
// throw new IllegalArgumentException("method may not be null");
// }
// this.method = method;
// this.lesson = new RbVariableInjector(lesson, method).injectLessonVariables();
// this.displayIncompleteException = displayIncompleteException;
// }
//
// public KoanMethod(String lesson, KoanElementAttributes koanAttributes) throws SecurityException, NoSuchMethodException {
// this( lesson,
// KoanClassLoader.getInstance().loadClass(koanAttributes.className, listener)
// .getMethod(koanAttributes.name),
// !"false".equalsIgnoreCase(koanAttributes.displayIncompleteKoanException));
// }
//
// public String getLesson() {
// return lesson;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public boolean displayIncompleteException() {
// return displayIncompleteException;
// }
//
// public KoanMethod clone(Method method){
// return new KoanMethod(lesson, method, displayIncompleteException);
// }
//
// @Override public String toString(){
// return "{"+getMethod().getName()
// +" : "+ (lesson.length() > 20 ? lesson.substring(0, 20) + "..." : lesson)+"}";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (displayIncompleteException ? 1231 : 1237);
// result = prime * result + ((lesson == null) ? 0 : lesson.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// KoanMethod other = (KoanMethod) obj;
// if (displayIncompleteException != other.displayIncompleteException)
// return false;
// if (lesson == null) {
// if (other.lesson != null)
// return false;
// } else if (!lesson.equals(other.lesson))
// return false;
// return true;
// }
//
//
// }
// Path: lib/src/main/java/com/sandwich/koan/result/KoanMethodResult.java
import com.sandwich.koan.KoanMethod;
package com.sandwich.koan.result;
public class KoanMethodResult {
public final static KoanMethodResult PASSED = new KoanMethodResult(null,"PASSED","PASSED");
private final String message;
private final String lineNumber; | private final KoanMethod failingMethod; |
matyb/java-koans | koans/src/beginner/AboutObjects.java | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
| import com.sandwich.koan.Koan;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals; | package beginner;
public class AboutObjects {
@Koan
public void newObjectInstancesCanBeCreatedDirectly() { | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
// Path: koans/src/beginner/AboutObjects.java
import com.sandwich.koan.Koan;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals;
package beginner;
public class AboutObjects {
@Koan
public void newObjectInstancesCanBeCreatedDirectly() { | assertEquals(new Object() instanceof Object, __); |
matyb/java-koans | koans/src/beginner/AboutConditionals.java | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
| import com.sandwich.koan.Koan;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals; | package beginner;
public class AboutConditionals {
@Koan
public void basicIf() {
int x = 1;
if (true) {
x++;
} | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
// Path: koans/src/beginner/AboutConditionals.java
import com.sandwich.koan.Koan;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals;
package beginner;
public class AboutConditionals {
@Koan
public void basicIf() {
int x = 1;
if (true) {
x++;
} | assertEquals(x, __); |
matyb/java-koans | lib/src/main/java/com/sandwich/koan/ApplicationSettings.java | // Path: lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java
// public abstract class DirectoryManager {
//
// private DirectoryManager(){}
//
// private static DirectorySet production = new ProductionDirectories();
// private static DirectorySet instance = production;
//
// public static final String FILESYSTEM_SEPARATOR = System.getProperty("file.separator");
//
// public static void setDirectorySet(DirectorySet lInstance){
// instance = lInstance;
// }
//
// public static String getMainDir(){
// return constructMainDir(instance);
// }
//
// public static String getProdMainDir() {
// return constructMainDir(production);
// }
//
// private static String constructMainDir(DirectorySet directories){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir());
// }
//
// public static String getConfigDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir());
// }
//
// public static String getSourceDir(){
// return constructProjectDir(instance, instance.getSourceDir());
// }
//
// public static String getProdSourceDir(){
// return constructProjectDir(production, production.getSourceDir());
// }
//
// public static String getBinDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getBinaryDir());
// }
//
// public static String getDataDir() {
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getDataDir());
// }
//
// private static String constructProjectDir(DirectorySet directories, String childDir){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir(),
// childDir);
// }
//
// public static String getProjectLibraryDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getLibrariesDir());
// }
//
// public static String getProjectI18nDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir(),
// instance.getI18nDir());
// }
//
// public static String getProjectDataSourceDir() {
// return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
// }
//
// public static String getDataFile() {
// return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
// }
//
// /**
// * Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
// *
// * @param folders
// * @return concatenated folders w/ file separators
// */
// public static String injectFileSystemSeparators(String...folders){
// StringBuilder builder = new StringBuilder();
// for(String folder : folders){
// if(FILESYSTEM_SEPARATOR.equals(folder)){
// continue;
// }
// builder.append(FILESYSTEM_SEPARATOR);
// while(folder.startsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(1);
// }
// while(folder.endsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
// }
// builder.append(folder);
// }
// String constructedFolder = builder.toString();
// if(ApplicationUtils.isWindows()){
// if(constructedFolder.startsWith(FILESYSTEM_SEPARATOR)){
// constructedFolder = constructedFolder.substring(1);
// }
// constructedFolder = constructedFolder.replace("%20", " ");
// }
// return constructedFolder;
// }
//
// }
| import java.io.FileInputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import com.sandwich.util.io.directories.DirectoryManager; | return getConfigBundle().getString("exit_character").charAt(0);
}
public static String getPathXmlFileName(){
return getConfigBundle().getString("path_xml_filename");
}
public static long getFileCompilationTimeoutInMs(){
return Long.valueOf(getConfigBundle().getString("compile_timeout_in_ms"));
}
public static String getMonitorIgnorePattern(){
return getConfigBundle().getString("ignore_from_monitoring");
}
private static boolean isEqual(String value, Object e2, boolean ignoreCase){
if(value == e2){
return true;
}
if(value != null){
String stringValue = String.valueOf(e2);
return ignoreCase ? value.equalsIgnoreCase(stringValue) : value.equals(stringValue);
}
return false;
}
private static ResourceBundle getConfigBundle(){
if(CONFIG_BUNDLE == null){
try {
CONFIG_BUNDLE = new PropertyResourceBundle(new FileInputStream( | // Path: lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java
// public abstract class DirectoryManager {
//
// private DirectoryManager(){}
//
// private static DirectorySet production = new ProductionDirectories();
// private static DirectorySet instance = production;
//
// public static final String FILESYSTEM_SEPARATOR = System.getProperty("file.separator");
//
// public static void setDirectorySet(DirectorySet lInstance){
// instance = lInstance;
// }
//
// public static String getMainDir(){
// return constructMainDir(instance);
// }
//
// public static String getProdMainDir() {
// return constructMainDir(production);
// }
//
// private static String constructMainDir(DirectorySet directories){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir());
// }
//
// public static String getConfigDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir());
// }
//
// public static String getSourceDir(){
// return constructProjectDir(instance, instance.getSourceDir());
// }
//
// public static String getProdSourceDir(){
// return constructProjectDir(production, production.getSourceDir());
// }
//
// public static String getBinDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getBinaryDir());
// }
//
// public static String getDataDir() {
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getDataDir());
// }
//
// private static String constructProjectDir(DirectorySet directories, String childDir){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir(),
// childDir);
// }
//
// public static String getProjectLibraryDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getLibrariesDir());
// }
//
// public static String getProjectI18nDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir(),
// instance.getI18nDir());
// }
//
// public static String getProjectDataSourceDir() {
// return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
// }
//
// public static String getDataFile() {
// return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
// }
//
// /**
// * Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
// *
// * @param folders
// * @return concatenated folders w/ file separators
// */
// public static String injectFileSystemSeparators(String...folders){
// StringBuilder builder = new StringBuilder();
// for(String folder : folders){
// if(FILESYSTEM_SEPARATOR.equals(folder)){
// continue;
// }
// builder.append(FILESYSTEM_SEPARATOR);
// while(folder.startsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(1);
// }
// while(folder.endsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
// }
// builder.append(folder);
// }
// String constructedFolder = builder.toString();
// if(ApplicationUtils.isWindows()){
// if(constructedFolder.startsWith(FILESYSTEM_SEPARATOR)){
// constructedFolder = constructedFolder.substring(1);
// }
// constructedFolder = constructedFolder.replace("%20", " ");
// }
// return constructedFolder;
// }
//
// }
// Path: lib/src/main/java/com/sandwich/koan/ApplicationSettings.java
import java.io.FileInputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import com.sandwich.util.io.directories.DirectoryManager;
return getConfigBundle().getString("exit_character").charAt(0);
}
public static String getPathXmlFileName(){
return getConfigBundle().getString("path_xml_filename");
}
public static long getFileCompilationTimeoutInMs(){
return Long.valueOf(getConfigBundle().getString("compile_timeout_in_ms"));
}
public static String getMonitorIgnorePattern(){
return getConfigBundle().getString("ignore_from_monitoring");
}
private static boolean isEqual(String value, Object e2, boolean ignoreCase){
if(value == e2){
return true;
}
if(value != null){
String stringValue = String.valueOf(e2);
return ignoreCase ? value.equalsIgnoreCase(stringValue) : value.equals(stringValue);
}
return false;
}
private static ResourceBundle getConfigBundle(){
if(CONFIG_BUNDLE == null){
try {
CONFIG_BUNDLE = new PropertyResourceBundle(new FileInputStream( | DirectoryManager.injectFileSystemSeparators( |
matyb/java-koans | lib/src/main/java/com/sandwich/util/io/FileMonitor.java | // Path: lib/src/main/java/com/sandwich/koan/ApplicationSettings.java
// public class ApplicationSettings {
//
// private static ResourceBundle CONFIG_BUNDLE;
//
// private static boolean debug;
//
// public static void setDebug(boolean debug2) {
// debug = debug2;
// }
//
// public static boolean isDebug(){
// return debug || isEqual(getConfigBundle().getString("debug"), true, true);
// }
//
// public static boolean isEncouragementEnabled(){
// return isEqual(getConfigBundle().getString("enable_encouragement"), true, true);
// }
//
// public static boolean isExpectationResultVisible(){
// return isEqual(getConfigBundle().getString("enable_expectation_result"), true, true);
// }
//
// public static boolean isInteractive(){
// return isEqual(getConfigBundle().getString("interactive"), true, true);
// }
//
// public static char getExitChar(){
// return getConfigBundle().getString("exit_character").charAt(0);
// }
//
// public static String getPathXmlFileName(){
// return getConfigBundle().getString("path_xml_filename");
// }
//
// public static long getFileCompilationTimeoutInMs(){
// return Long.valueOf(getConfigBundle().getString("compile_timeout_in_ms"));
// }
//
// public static String getMonitorIgnorePattern(){
// return getConfigBundle().getString("ignore_from_monitoring");
// }
//
// private static boolean isEqual(String value, Object e2, boolean ignoreCase){
// if(value == e2){
// return true;
// }
// if(value != null){
// String stringValue = String.valueOf(e2);
// return ignoreCase ? value.equalsIgnoreCase(stringValue) : value.equals(stringValue);
// }
// return false;
// }
//
// private static ResourceBundle getConfigBundle(){
// if(CONFIG_BUNDLE == null){
// try {
// CONFIG_BUNDLE = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getConfigDir(), "config.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// return CONFIG_BUNDLE;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import com.sandwich.koan.ApplicationSettings; | listeners.remove(listener);
}
synchronized void notifyListeners(){
try {
Map<String, Long> currentHashes = getFilesystemHashes();
for(String fileName : currentHashes.keySet()){
Long currentHash = currentHashes.get(fileName);
Long previousHash = fileHashesByDirectory.get(fileName);
fileHashesByDirectory.put(fileName, currentHash);
File file = new File(fileName);
for(FileListener listener : listeners){
if(previousHash == null && currentHash != null){
listener.newFile(file);
}else if(currentHash == null && previousHash != null){
listener.fileDeleted(file);
}else if(!currentHash.equals(previousHash)){
listener.fileSaved(file);
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Map<String, Long> getFilesystemHashes() throws IOException {
final HashMap<String,Long> fileHashes = new HashMap<String,Long>(); | // Path: lib/src/main/java/com/sandwich/koan/ApplicationSettings.java
// public class ApplicationSettings {
//
// private static ResourceBundle CONFIG_BUNDLE;
//
// private static boolean debug;
//
// public static void setDebug(boolean debug2) {
// debug = debug2;
// }
//
// public static boolean isDebug(){
// return debug || isEqual(getConfigBundle().getString("debug"), true, true);
// }
//
// public static boolean isEncouragementEnabled(){
// return isEqual(getConfigBundle().getString("enable_encouragement"), true, true);
// }
//
// public static boolean isExpectationResultVisible(){
// return isEqual(getConfigBundle().getString("enable_expectation_result"), true, true);
// }
//
// public static boolean isInteractive(){
// return isEqual(getConfigBundle().getString("interactive"), true, true);
// }
//
// public static char getExitChar(){
// return getConfigBundle().getString("exit_character").charAt(0);
// }
//
// public static String getPathXmlFileName(){
// return getConfigBundle().getString("path_xml_filename");
// }
//
// public static long getFileCompilationTimeoutInMs(){
// return Long.valueOf(getConfigBundle().getString("compile_timeout_in_ms"));
// }
//
// public static String getMonitorIgnorePattern(){
// return getConfigBundle().getString("ignore_from_monitoring");
// }
//
// private static boolean isEqual(String value, Object e2, boolean ignoreCase){
// if(value == e2){
// return true;
// }
// if(value != null){
// String stringValue = String.valueOf(e2);
// return ignoreCase ? value.equalsIgnoreCase(stringValue) : value.equals(stringValue);
// }
// return false;
// }
//
// private static ResourceBundle getConfigBundle(){
// if(CONFIG_BUNDLE == null){
// try {
// CONFIG_BUNDLE = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getConfigDir(), "config.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// return CONFIG_BUNDLE;
// }
//
// }
// Path: lib/src/main/java/com/sandwich/util/io/FileMonitor.java
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import com.sandwich.koan.ApplicationSettings;
listeners.remove(listener);
}
synchronized void notifyListeners(){
try {
Map<String, Long> currentHashes = getFilesystemHashes();
for(String fileName : currentHashes.keySet()){
Long currentHash = currentHashes.get(fileName);
Long previousHash = fileHashesByDirectory.get(fileName);
fileHashesByDirectory.put(fileName, currentHash);
File file = new File(fileName);
for(FileListener listener : listeners){
if(previousHash == null && currentHash != null){
listener.newFile(file);
}else if(currentHash == null && previousHash != null){
listener.fileDeleted(file);
}else if(!currentHash.equals(previousHash)){
listener.fileSaved(file);
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Map<String, Long> getFilesystemHashes() throws IOException {
final HashMap<String,Long> fileHashes = new HashMap<String,Long>(); | new ForEachFileAction(ApplicationSettings.getMonitorIgnorePattern()){ |
matyb/java-koans | koans/src/java8/AboutStreams.java | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
| import com.sandwich.koan.Koan;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals; | package java8;
public class AboutStreams {
String str = "";
List<String> places = Arrays.asList("Belgrade", "Zagreb", "Sarajevo", "Skopje", "Ljubljana", "Podgorica");
@Koan
public void simpleCount() {
long count = places.stream().count(); | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String __ = Strings.getMessage("__");
// Path: koans/src/java8/AboutStreams.java
import com.sandwich.koan.Koan;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals;
package java8;
public class AboutStreams {
String str = "";
List<String> places = Arrays.asList("Belgrade", "Zagreb", "Sarajevo", "Skopje", "Ljubljana", "Podgorica");
@Koan
public void simpleCount() {
long count = places.stream().count(); | assertEquals(count, __); |
matyb/java-koans | lib/src/main/java/com/sandwich/util/io/FileMonitorFactory.java | // Path: lib/src/main/java/com/sandwich/koan/ApplicationSettings.java
// public class ApplicationSettings {
//
// private static ResourceBundle CONFIG_BUNDLE;
//
// private static boolean debug;
//
// public static void setDebug(boolean debug2) {
// debug = debug2;
// }
//
// public static boolean isDebug(){
// return debug || isEqual(getConfigBundle().getString("debug"), true, true);
// }
//
// public static boolean isEncouragementEnabled(){
// return isEqual(getConfigBundle().getString("enable_encouragement"), true, true);
// }
//
// public static boolean isExpectationResultVisible(){
// return isEqual(getConfigBundle().getString("enable_expectation_result"), true, true);
// }
//
// public static boolean isInteractive(){
// return isEqual(getConfigBundle().getString("interactive"), true, true);
// }
//
// public static char getExitChar(){
// return getConfigBundle().getString("exit_character").charAt(0);
// }
//
// public static String getPathXmlFileName(){
// return getConfigBundle().getString("path_xml_filename");
// }
//
// public static long getFileCompilationTimeoutInMs(){
// return Long.valueOf(getConfigBundle().getString("compile_timeout_in_ms"));
// }
//
// public static String getMonitorIgnorePattern(){
// return getConfigBundle().getString("ignore_from_monitoring");
// }
//
// private static boolean isEqual(String value, Object e2, boolean ignoreCase){
// if(value == e2){
// return true;
// }
// if(value != null){
// String stringValue = String.valueOf(e2);
// return ignoreCase ? value.equalsIgnoreCase(stringValue) : value.equals(stringValue);
// }
// return false;
// }
//
// private static ResourceBundle getConfigBundle(){
// if(CONFIG_BUNDLE == null){
// try {
// CONFIG_BUNDLE = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getConfigDir(), "config.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// return CONFIG_BUNDLE;
// }
//
// }
| import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.sandwich.koan.ApplicationSettings; | package com.sandwich.util.io;
public class FileMonitorFactory {
private static Map<String, FileMonitor> monitors = new LinkedHashMap<String, FileMonitor>();
public static final int SLEEP_TIME_IN_MS = 500;
static {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
public void run() {
for(FileMonitor monitor : monitors.values()){
monitor.close();
}
monitors.clear();
}
}));
Thread pollingThread = new Thread(new Runnable(){
public void run() {
do{ | // Path: lib/src/main/java/com/sandwich/koan/ApplicationSettings.java
// public class ApplicationSettings {
//
// private static ResourceBundle CONFIG_BUNDLE;
//
// private static boolean debug;
//
// public static void setDebug(boolean debug2) {
// debug = debug2;
// }
//
// public static boolean isDebug(){
// return debug || isEqual(getConfigBundle().getString("debug"), true, true);
// }
//
// public static boolean isEncouragementEnabled(){
// return isEqual(getConfigBundle().getString("enable_encouragement"), true, true);
// }
//
// public static boolean isExpectationResultVisible(){
// return isEqual(getConfigBundle().getString("enable_expectation_result"), true, true);
// }
//
// public static boolean isInteractive(){
// return isEqual(getConfigBundle().getString("interactive"), true, true);
// }
//
// public static char getExitChar(){
// return getConfigBundle().getString("exit_character").charAt(0);
// }
//
// public static String getPathXmlFileName(){
// return getConfigBundle().getString("path_xml_filename");
// }
//
// public static long getFileCompilationTimeoutInMs(){
// return Long.valueOf(getConfigBundle().getString("compile_timeout_in_ms"));
// }
//
// public static String getMonitorIgnorePattern(){
// return getConfigBundle().getString("ignore_from_monitoring");
// }
//
// private static boolean isEqual(String value, Object e2, boolean ignoreCase){
// if(value == e2){
// return true;
// }
// if(value != null){
// String stringValue = String.valueOf(e2);
// return ignoreCase ? value.equalsIgnoreCase(stringValue) : value.equals(stringValue);
// }
// return false;
// }
//
// private static ResourceBundle getConfigBundle(){
// if(CONFIG_BUNDLE == null){
// try {
// CONFIG_BUNDLE = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getConfigDir(), "config.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// return CONFIG_BUNDLE;
// }
//
// }
// Path: lib/src/main/java/com/sandwich/util/io/FileMonitorFactory.java
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.sandwich.koan.ApplicationSettings;
package com.sandwich.util.io;
public class FileMonitorFactory {
private static Map<String, FileMonitor> monitors = new LinkedHashMap<String, FileMonitor>();
public static final int SLEEP_TIME_IN_MS = 500;
static {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
public void run() {
for(FileMonitor monitor : monitors.values()){
monitor.close();
}
monitors.clear();
}
}));
Thread pollingThread = new Thread(new Runnable(){
public void run() {
do{ | if(ApplicationSettings.isInteractive()){ |
matyb/java-koans | lib/src/test/java/com/sandwich/util/io/FileOperationTest.java | // Path: lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java
// public abstract class DirectoryManager {
//
// private DirectoryManager(){}
//
// private static DirectorySet production = new ProductionDirectories();
// private static DirectorySet instance = production;
//
// public static final String FILESYSTEM_SEPARATOR = System.getProperty("file.separator");
//
// public static void setDirectorySet(DirectorySet lInstance){
// instance = lInstance;
// }
//
// public static String getMainDir(){
// return constructMainDir(instance);
// }
//
// public static String getProdMainDir() {
// return constructMainDir(production);
// }
//
// private static String constructMainDir(DirectorySet directories){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir());
// }
//
// public static String getConfigDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir());
// }
//
// public static String getSourceDir(){
// return constructProjectDir(instance, instance.getSourceDir());
// }
//
// public static String getProdSourceDir(){
// return constructProjectDir(production, production.getSourceDir());
// }
//
// public static String getBinDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getBinaryDir());
// }
//
// public static String getDataDir() {
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getDataDir());
// }
//
// private static String constructProjectDir(DirectorySet directories, String childDir){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir(),
// childDir);
// }
//
// public static String getProjectLibraryDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getLibrariesDir());
// }
//
// public static String getProjectI18nDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir(),
// instance.getI18nDir());
// }
//
// public static String getProjectDataSourceDir() {
// return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
// }
//
// public static String getDataFile() {
// return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
// }
//
// /**
// * Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
// *
// * @param folders
// * @return concatenated folders w/ file separators
// */
// public static String injectFileSystemSeparators(String...folders){
// StringBuilder builder = new StringBuilder();
// for(String folder : folders){
// if(FILESYSTEM_SEPARATOR.equals(folder)){
// continue;
// }
// builder.append(FILESYSTEM_SEPARATOR);
// while(folder.startsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(1);
// }
// while(folder.endsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
// }
// builder.append(folder);
// }
// String constructedFolder = builder.toString();
// if(ApplicationUtils.isWindows()){
// if(constructedFolder.startsWith(FILESYSTEM_SEPARATOR)){
// constructedFolder = constructedFolder.substring(1);
// }
// constructedFolder = constructedFolder.replace("%20", " ");
// }
// return constructedFolder;
// }
//
// }
| import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import com.sandwich.util.io.directories.DirectoryManager; | package com.sandwich.util.io;
public class FileOperationTest {
@Test
public void givenAnExistingFileNoFilterIsNotIgnored() throws Exception {
assertFalse(new FileOperation() {
public void onDirectory(File dir) throws IOException {}
public void onFile(File file) throws IOException {}
public void onNull(File nullFile) throws IOException {}
public void onNew(File newFile) throws IOException {} | // Path: lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java
// public abstract class DirectoryManager {
//
// private DirectoryManager(){}
//
// private static DirectorySet production = new ProductionDirectories();
// private static DirectorySet instance = production;
//
// public static final String FILESYSTEM_SEPARATOR = System.getProperty("file.separator");
//
// public static void setDirectorySet(DirectorySet lInstance){
// instance = lInstance;
// }
//
// public static String getMainDir(){
// return constructMainDir(instance);
// }
//
// public static String getProdMainDir() {
// return constructMainDir(production);
// }
//
// private static String constructMainDir(DirectorySet directories){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir());
// }
//
// public static String getConfigDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir());
// }
//
// public static String getSourceDir(){
// return constructProjectDir(instance, instance.getSourceDir());
// }
//
// public static String getProdSourceDir(){
// return constructProjectDir(production, production.getSourceDir());
// }
//
// public static String getBinDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getBinaryDir());
// }
//
// public static String getDataDir() {
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getDataDir());
// }
//
// private static String constructProjectDir(DirectorySet directories, String childDir){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir(),
// childDir);
// }
//
// public static String getProjectLibraryDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getLibrariesDir());
// }
//
// public static String getProjectI18nDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir(),
// instance.getI18nDir());
// }
//
// public static String getProjectDataSourceDir() {
// return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
// }
//
// public static String getDataFile() {
// return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
// }
//
// /**
// * Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
// *
// * @param folders
// * @return concatenated folders w/ file separators
// */
// public static String injectFileSystemSeparators(String...folders){
// StringBuilder builder = new StringBuilder();
// for(String folder : folders){
// if(FILESYSTEM_SEPARATOR.equals(folder)){
// continue;
// }
// builder.append(FILESYSTEM_SEPARATOR);
// while(folder.startsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(1);
// }
// while(folder.endsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
// }
// builder.append(folder);
// }
// String constructedFolder = builder.toString();
// if(ApplicationUtils.isWindows()){
// if(constructedFolder.startsWith(FILESYSTEM_SEPARATOR)){
// constructedFolder = constructedFolder.substring(1);
// }
// constructedFolder = constructedFolder.replace("%20", " ");
// }
// return constructedFolder;
// }
//
// }
// Path: lib/src/test/java/com/sandwich/util/io/FileOperationTest.java
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import com.sandwich.util.io.directories.DirectoryManager;
package com.sandwich.util.io;
public class FileOperationTest {
@Test
public void givenAnExistingFileNoFilterIsNotIgnored() throws Exception {
assertFalse(new FileOperation() {
public void onDirectory(File dir) throws IOException {}
public void onFile(File file) throws IOException {}
public void onNull(File nullFile) throws IOException {}
public void onNew(File newFile) throws IOException {} | }.isIgnored(new File(DirectoryManager.getBinDir()))); |
matyb/java-koans | lib/src/main/java/com/sandwich/util/io/filecompiler/FileCompilerAction.java | // Path: lib/src/main/java/com/sandwich/util/io/ForEachFileAction.java
// public abstract class ForEachFileAction extends ExistingFileAction {
//
// public ForEachFileAction(String... strings) {
// super(strings);
// }
//
// public void onDirectory(File dir) throws IOException {
// for (String fileName : dir.list()) {
// operate(new File(dir, fileName));
// }
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/util/io/StreamUtils.java
// public class StreamUtils {
//
// public static String convertStreamToString(InputStream stream) {
// Scanner scanner = new Scanner(stream);
// try {
// return scanner.useDelimiter("\\A").next();
// } catch (NoSuchElementException e) {
// return "";
// } finally {
// scanner.close();
// }
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import com.sandwich.util.ExceptionUtils;
import com.sandwich.util.io.ForEachFileAction;
import com.sandwich.util.io.StreamUtils; | this(destination, errorHandler, 1000, classPaths);
}
public FileCompilerAction(File destination,
CompilationListener errorHandler, long timeout, String[] classPaths) {
if(destination == null){
throw new IllegalArgumentException("the destination path is required");
}
this.destinationPath = destination.getAbsolutePath();
this.classPaths = classPaths;
this.compilationListener = errorHandler == null ? LOGGING_HANDLER : errorHandler;
this.timeout = timeout;
}
public void onFile(File src) throws IOException {
String fileName = src.getName();
if (CompilerConfig.isSourceFile(fileName)) {
String[] command = CompilerConfig.getCompilationCommand(src, destinationPath, getClasspath());
try{
Process p = Runtime.getRuntime().exec(command);
try {
executeWithTimeout(src, command, p, timeout);
} catch (IllegalThreadStateException x) {
compilationListener.compilationFailed(src, command,
255, "Compilation took longer than "+timeout+" ms.\n" +
"It is likely that the compiler has locked up compiling this file.\n" +
"Please revert your last change and try something different.", x);
} catch (Exception x) {
x.printStackTrace();
compilationListener.compilationFailed(src, command, | // Path: lib/src/main/java/com/sandwich/util/io/ForEachFileAction.java
// public abstract class ForEachFileAction extends ExistingFileAction {
//
// public ForEachFileAction(String... strings) {
// super(strings);
// }
//
// public void onDirectory(File dir) throws IOException {
// for (String fileName : dir.list()) {
// operate(new File(dir, fileName));
// }
// }
//
// }
//
// Path: lib/src/main/java/com/sandwich/util/io/StreamUtils.java
// public class StreamUtils {
//
// public static String convertStreamToString(InputStream stream) {
// Scanner scanner = new Scanner(stream);
// try {
// return scanner.useDelimiter("\\A").next();
// } catch (NoSuchElementException e) {
// return "";
// } finally {
// scanner.close();
// }
// }
//
// }
// Path: lib/src/main/java/com/sandwich/util/io/filecompiler/FileCompilerAction.java
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import com.sandwich.util.ExceptionUtils;
import com.sandwich.util.io.ForEachFileAction;
import com.sandwich.util.io.StreamUtils;
this(destination, errorHandler, 1000, classPaths);
}
public FileCompilerAction(File destination,
CompilationListener errorHandler, long timeout, String[] classPaths) {
if(destination == null){
throw new IllegalArgumentException("the destination path is required");
}
this.destinationPath = destination.getAbsolutePath();
this.classPaths = classPaths;
this.compilationListener = errorHandler == null ? LOGGING_HANDLER : errorHandler;
this.timeout = timeout;
}
public void onFile(File src) throws IOException {
String fileName = src.getName();
if (CompilerConfig.isSourceFile(fileName)) {
String[] command = CompilerConfig.getCompilationCommand(src, destinationPath, getClasspath());
try{
Process p = Runtime.getRuntime().exec(command);
try {
executeWithTimeout(src, command, p, timeout);
} catch (IllegalThreadStateException x) {
compilationListener.compilationFailed(src, command,
255, "Compilation took longer than "+timeout+" ms.\n" +
"It is likely that the compiler has locked up compiling this file.\n" +
"Please revert your last change and try something different.", x);
} catch (Exception x) {
x.printStackTrace();
compilationListener.compilationFailed(src, command, | p.exitValue(), StreamUtils.convertStreamToString(p.getErrorStream()), x); |
matyb/java-koans | lib/src/main/java/com/sandwich/util/Strings.java | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String PERIOD = ".";
//
// Path: lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java
// public abstract class DirectoryManager {
//
// private DirectoryManager(){}
//
// private static DirectorySet production = new ProductionDirectories();
// private static DirectorySet instance = production;
//
// public static final String FILESYSTEM_SEPARATOR = System.getProperty("file.separator");
//
// public static void setDirectorySet(DirectorySet lInstance){
// instance = lInstance;
// }
//
// public static String getMainDir(){
// return constructMainDir(instance);
// }
//
// public static String getProdMainDir() {
// return constructMainDir(production);
// }
//
// private static String constructMainDir(DirectorySet directories){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir());
// }
//
// public static String getConfigDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir());
// }
//
// public static String getSourceDir(){
// return constructProjectDir(instance, instance.getSourceDir());
// }
//
// public static String getProdSourceDir(){
// return constructProjectDir(production, production.getSourceDir());
// }
//
// public static String getBinDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getBinaryDir());
// }
//
// public static String getDataDir() {
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getDataDir());
// }
//
// private static String constructProjectDir(DirectorySet directories, String childDir){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir(),
// childDir);
// }
//
// public static String getProjectLibraryDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getLibrariesDir());
// }
//
// public static String getProjectI18nDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir(),
// instance.getI18nDir());
// }
//
// public static String getProjectDataSourceDir() {
// return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
// }
//
// public static String getDataFile() {
// return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
// }
//
// /**
// * Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
// *
// * @param folders
// * @return concatenated folders w/ file separators
// */
// public static String injectFileSystemSeparators(String...folders){
// StringBuilder builder = new StringBuilder();
// for(String folder : folders){
// if(FILESYSTEM_SEPARATOR.equals(folder)){
// continue;
// }
// builder.append(FILESYSTEM_SEPARATOR);
// while(folder.startsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(1);
// }
// while(folder.endsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
// }
// builder.append(folder);
// }
// String constructedFolder = builder.toString();
// if(ApplicationUtils.isWindows()){
// if(constructedFolder.startsWith(FILESYSTEM_SEPARATOR)){
// constructedFolder = constructedFolder.substring(1);
// }
// constructedFolder = constructedFolder.replace("%20", " ");
// }
// return constructedFolder;
// }
//
// }
| import static com.sandwich.koan.constant.KoanConstants.PERIOD;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sandwich.util.io.directories.DirectoryManager; | package com.sandwich.util;
public class Strings {
private static final ResourceBundle MESSAGES_BUNDLE = getMessagesBundle();
private static final String UNFOUND_PROP_VALUE_STRING = "!";
private Strings() {
}
public static String getMessage(String key) {
try {
return MESSAGES_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return new StringBuilder(UNFOUND_PROP_VALUE_STRING).append(key).append(UNFOUND_PROP_VALUE_STRING).toString();
}
}
public static String getMessage(Class<?> clazz, String key){ | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String PERIOD = ".";
//
// Path: lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java
// public abstract class DirectoryManager {
//
// private DirectoryManager(){}
//
// private static DirectorySet production = new ProductionDirectories();
// private static DirectorySet instance = production;
//
// public static final String FILESYSTEM_SEPARATOR = System.getProperty("file.separator");
//
// public static void setDirectorySet(DirectorySet lInstance){
// instance = lInstance;
// }
//
// public static String getMainDir(){
// return constructMainDir(instance);
// }
//
// public static String getProdMainDir() {
// return constructMainDir(production);
// }
//
// private static String constructMainDir(DirectorySet directories){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir());
// }
//
// public static String getConfigDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir());
// }
//
// public static String getSourceDir(){
// return constructProjectDir(instance, instance.getSourceDir());
// }
//
// public static String getProdSourceDir(){
// return constructProjectDir(production, production.getSourceDir());
// }
//
// public static String getBinDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getBinaryDir());
// }
//
// public static String getDataDir() {
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getDataDir());
// }
//
// private static String constructProjectDir(DirectorySet directories, String childDir){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir(),
// childDir);
// }
//
// public static String getProjectLibraryDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getLibrariesDir());
// }
//
// public static String getProjectI18nDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir(),
// instance.getI18nDir());
// }
//
// public static String getProjectDataSourceDir() {
// return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
// }
//
// public static String getDataFile() {
// return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
// }
//
// /**
// * Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
// *
// * @param folders
// * @return concatenated folders w/ file separators
// */
// public static String injectFileSystemSeparators(String...folders){
// StringBuilder builder = new StringBuilder();
// for(String folder : folders){
// if(FILESYSTEM_SEPARATOR.equals(folder)){
// continue;
// }
// builder.append(FILESYSTEM_SEPARATOR);
// while(folder.startsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(1);
// }
// while(folder.endsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
// }
// builder.append(folder);
// }
// String constructedFolder = builder.toString();
// if(ApplicationUtils.isWindows()){
// if(constructedFolder.startsWith(FILESYSTEM_SEPARATOR)){
// constructedFolder = constructedFolder.substring(1);
// }
// constructedFolder = constructedFolder.replace("%20", " ");
// }
// return constructedFolder;
// }
//
// }
// Path: lib/src/main/java/com/sandwich/util/Strings.java
import static com.sandwich.koan.constant.KoanConstants.PERIOD;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sandwich.util.io.directories.DirectoryManager;
package com.sandwich.util;
public class Strings {
private static final ResourceBundle MESSAGES_BUNDLE = getMessagesBundle();
private static final String UNFOUND_PROP_VALUE_STRING = "!";
private Strings() {
}
public static String getMessage(String key) {
try {
return MESSAGES_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return new StringBuilder(UNFOUND_PROP_VALUE_STRING).append(key).append(UNFOUND_PROP_VALUE_STRING).toString();
}
}
public static String getMessage(Class<?> clazz, String key){ | return Strings.getMessage(new StringBuilder(clazz.getSimpleName()).append(PERIOD).append(key).toString()); |
matyb/java-koans | lib/src/main/java/com/sandwich/util/Strings.java | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String PERIOD = ".";
//
// Path: lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java
// public abstract class DirectoryManager {
//
// private DirectoryManager(){}
//
// private static DirectorySet production = new ProductionDirectories();
// private static DirectorySet instance = production;
//
// public static final String FILESYSTEM_SEPARATOR = System.getProperty("file.separator");
//
// public static void setDirectorySet(DirectorySet lInstance){
// instance = lInstance;
// }
//
// public static String getMainDir(){
// return constructMainDir(instance);
// }
//
// public static String getProdMainDir() {
// return constructMainDir(production);
// }
//
// private static String constructMainDir(DirectorySet directories){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir());
// }
//
// public static String getConfigDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir());
// }
//
// public static String getSourceDir(){
// return constructProjectDir(instance, instance.getSourceDir());
// }
//
// public static String getProdSourceDir(){
// return constructProjectDir(production, production.getSourceDir());
// }
//
// public static String getBinDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getBinaryDir());
// }
//
// public static String getDataDir() {
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getDataDir());
// }
//
// private static String constructProjectDir(DirectorySet directories, String childDir){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir(),
// childDir);
// }
//
// public static String getProjectLibraryDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getLibrariesDir());
// }
//
// public static String getProjectI18nDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir(),
// instance.getI18nDir());
// }
//
// public static String getProjectDataSourceDir() {
// return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
// }
//
// public static String getDataFile() {
// return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
// }
//
// /**
// * Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
// *
// * @param folders
// * @return concatenated folders w/ file separators
// */
// public static String injectFileSystemSeparators(String...folders){
// StringBuilder builder = new StringBuilder();
// for(String folder : folders){
// if(FILESYSTEM_SEPARATOR.equals(folder)){
// continue;
// }
// builder.append(FILESYSTEM_SEPARATOR);
// while(folder.startsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(1);
// }
// while(folder.endsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
// }
// builder.append(folder);
// }
// String constructedFolder = builder.toString();
// if(ApplicationUtils.isWindows()){
// if(constructedFolder.startsWith(FILESYSTEM_SEPARATOR)){
// constructedFolder = constructedFolder.substring(1);
// }
// constructedFolder = constructedFolder.replace("%20", " ");
// }
// return constructedFolder;
// }
//
// }
| import static com.sandwich.koan.constant.KoanConstants.PERIOD;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sandwich.util.io.directories.DirectoryManager; | }
public static String getMessage(Class<?> clazz, String key){
return Strings.getMessage(new StringBuilder(clazz.getSimpleName()).append(PERIOD).append(key).toString());
}
public static String[] getMessages(Class<?> clazz, String key) {
String[] tmp = getMessage(clazz, key).split(",");
String[] trimmed = new String[tmp.length];
for(int i = 0; i < tmp.length; i++){
trimmed[i] = tmp[i].trim();
}
return trimmed;
}
private static ResourceBundle getMessagesBundle(){
if(MESSAGES_BUNDLE == null){
return createResourceBundle();
}
return MESSAGES_BUNDLE;
}
/**
* conditionally create messages bundle for proper locale, not on classpath so need to handle manually
* @return a resource bundle for default locale, or USA if default locale's language has no translated messages
*/
static ResourceBundle createResourceBundle() {
ResourceBundle temp = null;
try {
temp = new PropertyResourceBundle(new FileInputStream( | // Path: lib/src/main/java/com/sandwich/koan/constant/KoanConstants.java
// public static final String PERIOD = ".";
//
// Path: lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java
// public abstract class DirectoryManager {
//
// private DirectoryManager(){}
//
// private static DirectorySet production = new ProductionDirectories();
// private static DirectorySet instance = production;
//
// public static final String FILESYSTEM_SEPARATOR = System.getProperty("file.separator");
//
// public static void setDirectorySet(DirectorySet lInstance){
// instance = lInstance;
// }
//
// public static String getMainDir(){
// return constructMainDir(instance);
// }
//
// public static String getProdMainDir() {
// return constructMainDir(production);
// }
//
// private static String constructMainDir(DirectorySet directories){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir());
// }
//
// public static String getConfigDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir());
// }
//
// public static String getSourceDir(){
// return constructProjectDir(instance, instance.getSourceDir());
// }
//
// public static String getProdSourceDir(){
// return constructProjectDir(production, production.getSourceDir());
// }
//
// public static String getBinDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getBinaryDir());
// }
//
// public static String getDataDir() {
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getDataDir());
// }
//
// private static String constructProjectDir(DirectorySet directories, String childDir){
// return injectFileSystemSeparators( directories.getBaseDir(),
// directories.getProjectDir(),
// childDir);
// }
//
// public static String getProjectLibraryDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getLibrariesDir());
// }
//
// public static String getProjectI18nDir(){
// return injectFileSystemSeparators( instance.getBaseDir(),
// production.getProjectDir(),
// instance.getAppDir(),
// instance.getConfigDir(),
// instance.getI18nDir());
// }
//
// public static String getProjectDataSourceDir() {
// return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
// }
//
// public static String getDataFile() {
// return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
// }
//
// /**
// * Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
// *
// * @param folders
// * @return concatenated folders w/ file separators
// */
// public static String injectFileSystemSeparators(String...folders){
// StringBuilder builder = new StringBuilder();
// for(String folder : folders){
// if(FILESYSTEM_SEPARATOR.equals(folder)){
// continue;
// }
// builder.append(FILESYSTEM_SEPARATOR);
// while(folder.startsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(1);
// }
// while(folder.endsWith(FILESYSTEM_SEPARATOR)){
// folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
// }
// builder.append(folder);
// }
// String constructedFolder = builder.toString();
// if(ApplicationUtils.isWindows()){
// if(constructedFolder.startsWith(FILESYSTEM_SEPARATOR)){
// constructedFolder = constructedFolder.substring(1);
// }
// constructedFolder = constructedFolder.replace("%20", " ");
// }
// return constructedFolder;
// }
//
// }
// Path: lib/src/main/java/com/sandwich/util/Strings.java
import static com.sandwich.koan.constant.KoanConstants.PERIOD;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sandwich.util.io.directories.DirectoryManager;
}
public static String getMessage(Class<?> clazz, String key){
return Strings.getMessage(new StringBuilder(clazz.getSimpleName()).append(PERIOD).append(key).toString());
}
public static String[] getMessages(Class<?> clazz, String key) {
String[] tmp = getMessage(clazz, key).split(",");
String[] trimmed = new String[tmp.length];
for(int i = 0; i < tmp.length; i++){
trimmed[i] = tmp[i].trim();
}
return trimmed;
}
private static ResourceBundle getMessagesBundle(){
if(MESSAGES_BUNDLE == null){
return createResourceBundle();
}
return MESSAGES_BUNDLE;
}
/**
* conditionally create messages bundle for proper locale, not on classpath so need to handle manually
* @return a resource bundle for default locale, or USA if default locale's language has no translated messages
*/
static ResourceBundle createResourceBundle() {
ResourceBundle temp = null;
try {
temp = new PropertyResourceBundle(new FileInputStream( | DirectoryManager.injectFileSystemSeparators( |
matyb/java-koans | lib/src/main/java/com/sandwich/koan/cmdline/behavior/AbstractArgumentBehavior.java | // Path: lib/src/main/java/com/sandwich/util/Strings.java
// public class Strings {
//
// private static final ResourceBundle MESSAGES_BUNDLE = getMessagesBundle();
// private static final String UNFOUND_PROP_VALUE_STRING = "!";
//
// private Strings() {
// }
//
// public static String getMessage(String key) {
// try {
// return MESSAGES_BUNDLE.getString(key);
// } catch (MissingResourceException e) {
// return new StringBuilder(UNFOUND_PROP_VALUE_STRING).append(key).append(UNFOUND_PROP_VALUE_STRING).toString();
// }
// }
//
// public static String getMessage(Class<?> clazz, String key){
// return Strings.getMessage(new StringBuilder(clazz.getSimpleName()).append(PERIOD).append(key).toString());
// }
//
// public static String[] getMessages(Class<?> clazz, String key) {
// String[] tmp = getMessage(clazz, key).split(",");
// String[] trimmed = new String[tmp.length];
// for(int i = 0; i < tmp.length; i++){
// trimmed[i] = tmp[i].trim();
// }
// return trimmed;
// }
//
// private static ResourceBundle getMessagesBundle(){
// if(MESSAGES_BUNDLE == null){
// return createResourceBundle();
// }
// return MESSAGES_BUNDLE;
// }
//
// /**
// * conditionally create messages bundle for proper locale, not on classpath so need to handle manually
// * @return a resource bundle for default locale, or USA if default locale's language has no translated messages
// */
// static ResourceBundle createResourceBundle() {
// ResourceBundle temp = null;
// try {
// temp = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getProjectI18nDir(),
// new StringBuilder("messages_").append(
// Locale.getDefault().getLanguage()).append(
// ".properties").toString())));
// } catch(FileNotFoundException x) {
// try {
// Logger.getLogger(Strings.class.getName()).log(Level.INFO, "Your default language is not supported yet. "+x.getLocalizedMessage());
// temp = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getProjectI18nDir(), "messages_en.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return temp;
// }
//
// public static boolean wasNotFound(String lesson) {
// return lesson.startsWith(UNFOUND_PROP_VALUE_STRING) && lesson.endsWith(UNFOUND_PROP_VALUE_STRING);
// }
// }
| import com.sandwich.util.Strings; | package com.sandwich.koan.cmdline.behavior;
public abstract class AbstractArgumentBehavior implements ArgumentBehavior{
public String getErrorMessage() { | // Path: lib/src/main/java/com/sandwich/util/Strings.java
// public class Strings {
//
// private static final ResourceBundle MESSAGES_BUNDLE = getMessagesBundle();
// private static final String UNFOUND_PROP_VALUE_STRING = "!";
//
// private Strings() {
// }
//
// public static String getMessage(String key) {
// try {
// return MESSAGES_BUNDLE.getString(key);
// } catch (MissingResourceException e) {
// return new StringBuilder(UNFOUND_PROP_VALUE_STRING).append(key).append(UNFOUND_PROP_VALUE_STRING).toString();
// }
// }
//
// public static String getMessage(Class<?> clazz, String key){
// return Strings.getMessage(new StringBuilder(clazz.getSimpleName()).append(PERIOD).append(key).toString());
// }
//
// public static String[] getMessages(Class<?> clazz, String key) {
// String[] tmp = getMessage(clazz, key).split(",");
// String[] trimmed = new String[tmp.length];
// for(int i = 0; i < tmp.length; i++){
// trimmed[i] = tmp[i].trim();
// }
// return trimmed;
// }
//
// private static ResourceBundle getMessagesBundle(){
// if(MESSAGES_BUNDLE == null){
// return createResourceBundle();
// }
// return MESSAGES_BUNDLE;
// }
//
// /**
// * conditionally create messages bundle for proper locale, not on classpath so need to handle manually
// * @return a resource bundle for default locale, or USA if default locale's language has no translated messages
// */
// static ResourceBundle createResourceBundle() {
// ResourceBundle temp = null;
// try {
// temp = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getProjectI18nDir(),
// new StringBuilder("messages_").append(
// Locale.getDefault().getLanguage()).append(
// ".properties").toString())));
// } catch(FileNotFoundException x) {
// try {
// Logger.getLogger(Strings.class.getName()).log(Level.INFO, "Your default language is not supported yet. "+x.getLocalizedMessage());
// temp = new PropertyResourceBundle(new FileInputStream(
// DirectoryManager.injectFileSystemSeparators(
// DirectoryManager.getProjectI18nDir(), "messages_en.properties")));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return temp;
// }
//
// public static boolean wasNotFound(String lesson) {
// return lesson.startsWith(UNFOUND_PROP_VALUE_STRING) && lesson.endsWith(UNFOUND_PROP_VALUE_STRING);
// }
// }
// Path: lib/src/main/java/com/sandwich/koan/cmdline/behavior/AbstractArgumentBehavior.java
import com.sandwich.util.Strings;
package com.sandwich.koan.cmdline.behavior;
public abstract class AbstractArgumentBehavior implements ArgumentBehavior{
public String getErrorMessage() { | return Strings.getMessage(getClass(), "error"); |
matyb/java-koans | lib/src/main/java/com/sandwich/util/io/KoanSuiteCompilationListener.java | // Path: lib/src/main/java/com/sandwich/util/io/filecompiler/FileCompilerAction.java
// public class FileCompilerAction extends ForEachFileAction {
//
// private final String destinationPath;
// private final String[] classPaths;
// private CompilationListener compilationListener;
// private final long timeout;
// public static final CompilationListener LOGGING_HANDLER = new CompilationFailureLogger();
//
// public FileCompilerAction(File destination, CompilationListener errorHandler, String...classPaths){
// this(destination, errorHandler, 1000, classPaths);
// }
//
// public FileCompilerAction(File destination,
// CompilationListener errorHandler, long timeout, String[] classPaths) {
// if(destination == null){
// throw new IllegalArgumentException("the destination path is required");
// }
// this.destinationPath = destination.getAbsolutePath();
// this.classPaths = classPaths;
// this.compilationListener = errorHandler == null ? LOGGING_HANDLER : errorHandler;
// this.timeout = timeout;
// }
//
// public void onFile(File src) throws IOException {
// String fileName = src.getName();
// if (CompilerConfig.isSourceFile(fileName)) {
// String[] command = CompilerConfig.getCompilationCommand(src, destinationPath, getClasspath());
// try{
// Process p = Runtime.getRuntime().exec(command);
// try {
// executeWithTimeout(src, command, p, timeout);
// } catch (IllegalThreadStateException x) {
// compilationListener.compilationFailed(src, command,
// 255, "Compilation took longer than "+timeout+" ms.\n" +
// "It is likely that the compiler has locked up compiling this file.\n" +
// "Please revert your last change and try something different.", x);
// } catch (Exception x) {
// x.printStackTrace();
// compilationListener.compilationFailed(src, command,
// p.exitValue(), StreamUtils.convertStreamToString(p.getErrorStream()), x);
// }
// }catch(IOException x){
// if(x.getMessage().contains("Cannot run program")){
// String commandString = "";
// for(String segment : command){
// commandString += segment + " ";
// }
// commandString = commandString.trim();
// compilationListener.compilationFailed(src, command, 2,
// "Cannot execute:" + System.getProperty("line.separator") +
// commandString + System.getProperty("line.separator") +
// "Please check that the appropriate compiler (" + command[0] + ") is installed, is executable and is listed in your PATH environment variable value.", x);
// }
// }
// }
// }
//
// private void executeWithTimeout(final File src, final String[] command,
// final Process p, final long timeout) throws InterruptedException {
// ExecutorService executor = Executors.newCachedThreadPool();
// Callable<Object> task = new Callable<Object>() {
// public Object call() {
// try {
// if (p.waitFor() != 0) {
// compilationListener.compilationFailed(src, command, p
// .exitValue(), StreamUtils.convertStreamToString(p.getErrorStream()), null);
// } else {
// compilationListener.compilationSucceeded(src, command,
// StreamUtils.convertStreamToString(p.getInputStream()), null);
// }
// } catch (InterruptedException e) {
// compilationListener.compilationFailed(src, command, p.exitValue(),
// ExceptionUtils.convertToPopulatedStackTraceString(e), null);
// }
// return null;
// }
// };
// Future<Object> future = executor.submit(task);
// try {
// future.get(timeout, TimeUnit.MILLISECONDS);
// } catch (Exception e) {
// compilationListener.compilationFailed(src, command, p.exitValue(),
// ExceptionUtils.convertToPopulatedStackTraceString(e), null);
// }
// }
//
// private String getClasspath() {
// String classPath = "";
// for(String jar : classPaths) {
// classPath += jar + File.pathSeparatorChar;
// }
// return classPath;
// }
//
// }
| import java.io.File;
import com.sandwich.util.io.filecompiler.CompilationListener;
import com.sandwich.util.io.filecompiler.FileCompilerAction; | package com.sandwich.util.io;
public class KoanSuiteCompilationListener implements CompilationListener {
private boolean lastCompilationAttemptFailed = false;
private String lastMessageShown = null;
public void compilationFailed(File src, String[] command, int exitCode, String errorMessage, Throwable x) {
if(lastMessageShown == null || !errorMessage.trim().equals(lastMessageShown.trim())){ | // Path: lib/src/main/java/com/sandwich/util/io/filecompiler/FileCompilerAction.java
// public class FileCompilerAction extends ForEachFileAction {
//
// private final String destinationPath;
// private final String[] classPaths;
// private CompilationListener compilationListener;
// private final long timeout;
// public static final CompilationListener LOGGING_HANDLER = new CompilationFailureLogger();
//
// public FileCompilerAction(File destination, CompilationListener errorHandler, String...classPaths){
// this(destination, errorHandler, 1000, classPaths);
// }
//
// public FileCompilerAction(File destination,
// CompilationListener errorHandler, long timeout, String[] classPaths) {
// if(destination == null){
// throw new IllegalArgumentException("the destination path is required");
// }
// this.destinationPath = destination.getAbsolutePath();
// this.classPaths = classPaths;
// this.compilationListener = errorHandler == null ? LOGGING_HANDLER : errorHandler;
// this.timeout = timeout;
// }
//
// public void onFile(File src) throws IOException {
// String fileName = src.getName();
// if (CompilerConfig.isSourceFile(fileName)) {
// String[] command = CompilerConfig.getCompilationCommand(src, destinationPath, getClasspath());
// try{
// Process p = Runtime.getRuntime().exec(command);
// try {
// executeWithTimeout(src, command, p, timeout);
// } catch (IllegalThreadStateException x) {
// compilationListener.compilationFailed(src, command,
// 255, "Compilation took longer than "+timeout+" ms.\n" +
// "It is likely that the compiler has locked up compiling this file.\n" +
// "Please revert your last change and try something different.", x);
// } catch (Exception x) {
// x.printStackTrace();
// compilationListener.compilationFailed(src, command,
// p.exitValue(), StreamUtils.convertStreamToString(p.getErrorStream()), x);
// }
// }catch(IOException x){
// if(x.getMessage().contains("Cannot run program")){
// String commandString = "";
// for(String segment : command){
// commandString += segment + " ";
// }
// commandString = commandString.trim();
// compilationListener.compilationFailed(src, command, 2,
// "Cannot execute:" + System.getProperty("line.separator") +
// commandString + System.getProperty("line.separator") +
// "Please check that the appropriate compiler (" + command[0] + ") is installed, is executable and is listed in your PATH environment variable value.", x);
// }
// }
// }
// }
//
// private void executeWithTimeout(final File src, final String[] command,
// final Process p, final long timeout) throws InterruptedException {
// ExecutorService executor = Executors.newCachedThreadPool();
// Callable<Object> task = new Callable<Object>() {
// public Object call() {
// try {
// if (p.waitFor() != 0) {
// compilationListener.compilationFailed(src, command, p
// .exitValue(), StreamUtils.convertStreamToString(p.getErrorStream()), null);
// } else {
// compilationListener.compilationSucceeded(src, command,
// StreamUtils.convertStreamToString(p.getInputStream()), null);
// }
// } catch (InterruptedException e) {
// compilationListener.compilationFailed(src, command, p.exitValue(),
// ExceptionUtils.convertToPopulatedStackTraceString(e), null);
// }
// return null;
// }
// };
// Future<Object> future = executor.submit(task);
// try {
// future.get(timeout, TimeUnit.MILLISECONDS);
// } catch (Exception e) {
// compilationListener.compilationFailed(src, command, p.exitValue(),
// ExceptionUtils.convertToPopulatedStackTraceString(e), null);
// }
// }
//
// private String getClasspath() {
// String classPath = "";
// for(String jar : classPaths) {
// classPath += jar + File.pathSeparatorChar;
// }
// return classPath;
// }
//
// }
// Path: lib/src/main/java/com/sandwich/util/io/KoanSuiteCompilationListener.java
import java.io.File;
import com.sandwich.util.io.filecompiler.CompilationListener;
import com.sandwich.util.io.filecompiler.FileCompilerAction;
package com.sandwich.util.io;
public class KoanSuiteCompilationListener implements CompilationListener {
private boolean lastCompilationAttemptFailed = false;
private String lastMessageShown = null;
public void compilationFailed(File src, String[] command, int exitCode, String errorMessage, Throwable x) {
if(lastMessageShown == null || !errorMessage.trim().equals(lastMessageShown.trim())){ | FileCompilerAction.LOGGING_HANDLER.compilationFailed(src, command, exitCode, errorMessage, x); |
matyb/java-koans | lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java | // Path: lib/src/main/java/com/sandwich/koan/util/ApplicationUtils.java
// public class ApplicationUtils {
//
// private static SuitePresenterFactory suitePresenterFactory = new SuitePresenterFactory();
//
// static public boolean isFirstTimeAppHasBeenRun() {
// File dataDirectory = new File(DirectoryManager.getDataDir());
// return !dataDirectory.exists();
// }
//
// static public boolean isWindows(){
// return System.getProperty("os.name").toLowerCase().contains("win");
// }
//
// static public SuitePresenter getPresenter(){
// return suitePresenterFactory.create();
// }
//
// public static class SuitePresenterFactory {
// protected SuitePresenter create(){
// return new ConsolePresenter();
// }
// }
// }
| import com.sandwich.koan.util.ApplicationUtils; | public static String getProjectDataSourceDir() {
return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
}
public static String getDataFile() {
return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
}
/**
* Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
*
* @param folders
* @return concatenated folders w/ file separators
*/
public static String injectFileSystemSeparators(String...folders){
StringBuilder builder = new StringBuilder();
for(String folder : folders){
if(FILESYSTEM_SEPARATOR.equals(folder)){
continue;
}
builder.append(FILESYSTEM_SEPARATOR);
while(folder.startsWith(FILESYSTEM_SEPARATOR)){
folder = folder.substring(1);
}
while(folder.endsWith(FILESYSTEM_SEPARATOR)){
folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
}
builder.append(folder);
}
String constructedFolder = builder.toString(); | // Path: lib/src/main/java/com/sandwich/koan/util/ApplicationUtils.java
// public class ApplicationUtils {
//
// private static SuitePresenterFactory suitePresenterFactory = new SuitePresenterFactory();
//
// static public boolean isFirstTimeAppHasBeenRun() {
// File dataDirectory = new File(DirectoryManager.getDataDir());
// return !dataDirectory.exists();
// }
//
// static public boolean isWindows(){
// return System.getProperty("os.name").toLowerCase().contains("win");
// }
//
// static public SuitePresenter getPresenter(){
// return suitePresenterFactory.create();
// }
//
// public static class SuitePresenterFactory {
// protected SuitePresenter create(){
// return new ConsolePresenter();
// }
// }
// }
// Path: lib/src/main/java/com/sandwich/util/io/directories/DirectoryManager.java
import com.sandwich.koan.util.ApplicationUtils;
public static String getProjectDataSourceDir() {
return injectFileSystemSeparators(getDataDir(), instance.getSourceDir());
}
public static String getDataFile() {
return injectFileSystemSeparators(getConfigDir(), "file_hashes.dat");
}
/**
* Will take "home", "wilford", "liberty" and produce: "/home/wilford/liberty"
*
* @param folders
* @return concatenated folders w/ file separators
*/
public static String injectFileSystemSeparators(String...folders){
StringBuilder builder = new StringBuilder();
for(String folder : folders){
if(FILESYSTEM_SEPARATOR.equals(folder)){
continue;
}
builder.append(FILESYSTEM_SEPARATOR);
while(folder.startsWith(FILESYSTEM_SEPARATOR)){
folder = folder.substring(1);
}
while(folder.endsWith(FILESYSTEM_SEPARATOR)){
folder = folder.substring(0, folder.lastIndexOf(FILESYSTEM_SEPARATOR));
}
builder.append(folder);
}
String constructedFolder = builder.toString(); | if(ApplicationUtils.isWindows()){ |
flanglet/kanzi | java/src/main/java/kanzi/entropy/RiceGolombDecoder.java | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
| import kanzi.EntropyDecoder;
import kanzi.InputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 Riceress or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kanzi.entropy;
// Rice-Golomb Coder
public final class RiceGolombDecoder implements EntropyDecoder
{
private final boolean signed; | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
// Path: java/src/main/java/kanzi/entropy/RiceGolombDecoder.java
import kanzi.EntropyDecoder;
import kanzi.InputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 Riceress or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kanzi.entropy;
// Rice-Golomb Coder
public final class RiceGolombDecoder implements EntropyDecoder
{
private final boolean signed; | private final InputBitStream bitstream; |
flanglet/kanzi | java/src/main/java/kanzi/transform/SRT.java | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
| import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Sorted Rank Transform is typically used after a BWT to reduce the variance
// of the data prior to entropy coding.
public class SRT implements ByteTransform
{
private static final int MAX_HEADER_SIZE = 4*256;
private final int[] freqs;
private final byte[] symbols;
private final int[] r2s;
private final int[] s2r;
private final int[] buckets;
private final int[] bucketEnds;
public SRT()
{
this.freqs = new int[256];
this.symbols = new byte[256];
this.r2s = new int[256];
this.s2r = new int[256];
this.buckets = new int[256];
this.bucketEnds = new int[256];
}
public SRT(Map<String, Object> ctx)
{
this.freqs = new int[256];
this.symbols = new byte[256];
this.r2s = new int[256];
this.s2r = new int[256];
this.buckets = new int[256];
this.bucketEnds = new int[256];
}
@Override | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
// Path: java/src/main/java/kanzi/transform/SRT.java
import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Sorted Rank Transform is typically used after a BWT to reduce the variance
// of the data prior to entropy coding.
public class SRT implements ByteTransform
{
private static final int MAX_HEADER_SIZE = 4*256;
private final int[] freqs;
private final byte[] symbols;
private final int[] r2s;
private final int[] s2r;
private final int[] buckets;
private final int[] bucketEnds;
public SRT()
{
this.freqs = new int[256];
this.symbols = new byte[256];
this.r2s = new int[256];
this.s2r = new int[256];
this.buckets = new int[256];
this.bucketEnds = new int[256];
}
public SRT(Map<String, Object> ctx)
{
this.freqs = new int[256];
this.symbols = new byte[256];
this.r2s = new int[256];
this.s2r = new int[256];
this.buckets = new int[256];
this.bucketEnds = new int[256];
}
@Override | public boolean forward(SliceByteArray input, SliceByteArray output) |
flanglet/kanzi | java/src/test/java/kanzi/test/TestAbstractSort.java | // Path: java/src/main/java/kanzi/IntSorter.java
// public interface IntSorter
// {
// public boolean sort(int[] array, int idx, int len);
// }
| import java.util.Random;
import kanzi.IntSorter; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.test;
public class TestAbstractSort
{ | // Path: java/src/main/java/kanzi/IntSorter.java
// public interface IntSorter
// {
// public boolean sort(int[] array, int idx, int len);
// }
// Path: java/src/test/java/kanzi/test/TestAbstractSort.java
import java.util.Random;
import kanzi.IntSorter;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.test;
public class TestAbstractSort
{ | public static boolean testCorrectness(String sortName, IntSorter sorter, int iters) |
flanglet/kanzi | java/src/main/java/kanzi/transform/TransformFactory.java | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
| import java.util.Map;
import kanzi.ByteTransform; | case "EXE":
return EXE_TYPE;
case "FSD":
return FSD_TYPE;
case "NONE":
return NONE_TYPE;
default:
throw new IllegalArgumentException("Unknown transform type: '" + name + "'");
}
}
public Sequence newFunction(Map<String, Object> ctx, long functionType)
{
int nbtr = 0;
// Several transforms
for (int i=0; i<8; i++)
{
if (((functionType >>> (MAX_SHIFT-ONE_SHIFT*i)) & MASK) != NONE_TYPE)
nbtr++;
}
// Only null transforms ? Keep first.
if (nbtr == 0)
nbtr = 1;
| // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
// Path: java/src/main/java/kanzi/transform/TransformFactory.java
import java.util.Map;
import kanzi.ByteTransform;
case "EXE":
return EXE_TYPE;
case "FSD":
return FSD_TYPE;
case "NONE":
return NONE_TYPE;
default:
throw new IllegalArgumentException("Unknown transform type: '" + name + "'");
}
}
public Sequence newFunction(Map<String, Object> ctx, long functionType)
{
int nbtr = 0;
// Several transforms
for (int i=0; i<8; i++)
{
if (((functionType >>> (MAX_SHIFT-ONE_SHIFT*i)) & MASK) != NONE_TYPE)
nbtr++;
}
// Only null transforms ? Keep first.
if (nbtr == 0)
nbtr = 1;
| ByteTransform[] transforms = new ByteTransform[nbtr]; |
flanglet/kanzi | java/src/main/java/kanzi/transform/SBRT.java | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
| import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray; |
public SBRT(int mode)
{
if ((mode != MODE_MTF) && (mode != MODE_RANK) && (mode != MODE_TIMESTAMP))
throw new IllegalArgumentException("Invalid mode parameter");
this.prev = new int[256];
this.curr = new int[256];
this.symbols = new int[256];
this.ranks = new int[256];
this.mode = mode;
}
public SBRT(Map<String, Object> ctx)
{
final int m = (Integer) ctx.getOrDefault("sbrt", MODE_MTF);
if ((m != MODE_MTF) && (m != MODE_RANK) && (m != MODE_TIMESTAMP))
throw new IllegalArgumentException("Invalid mode parameter");
this.prev = new int[256];
this.curr = new int[256];
this.symbols = new int[256];
this.ranks = new int[256];
this.mode = m;
}
@Override | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
// Path: java/src/main/java/kanzi/transform/SBRT.java
import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray;
public SBRT(int mode)
{
if ((mode != MODE_MTF) && (mode != MODE_RANK) && (mode != MODE_TIMESTAMP))
throw new IllegalArgumentException("Invalid mode parameter");
this.prev = new int[256];
this.curr = new int[256];
this.symbols = new int[256];
this.ranks = new int[256];
this.mode = mode;
}
public SBRT(Map<String, Object> ctx)
{
final int m = (Integer) ctx.getOrDefault("sbrt", MODE_MTF);
if ((m != MODE_MTF) && (m != MODE_RANK) && (m != MODE_TIMESTAMP))
throw new IllegalArgumentException("Invalid mode parameter");
this.prev = new int[256];
this.curr = new int[256];
this.symbols = new int[256];
this.ranks = new int[256];
this.mode = m;
}
@Override | public boolean forward(SliceByteArray input, SliceByteArray output) |
flanglet/kanzi | java/src/main/java/kanzi/entropy/ExpGolombEncoder.java | // Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import kanzi.EntropyEncoder;
import kanzi.OutputBitStream; | 6737, 6736, 6735, 6734, 6733, 6732, 6731, 6730, 6729, 6728, 6727, 6726, 6725, 6724, 6723, 6722,
6721, 6720, 5695, 5694, 5693, 5692, 5691, 5690, 5689, 5688, 5687, 5686, 5685, 5684, 5683, 5682,
5681, 5680, 5679, 5678, 5677, 5676, 5675, 5674, 5673, 5672, 5671, 5670, 5669, 5668, 5667, 5666,
5665, 5664, 4639, 4638, 4637, 4636, 4635, 4634, 4633, 4632, 4631, 4630, 4629, 4628, 4627, 4626,
4625, 4624, 3599, 3598, 3597, 3596, 3595, 3594, 3593, 3592, 2567, 2566, 2565, 2564, 1539, 1538
},
// Signed
new int[]
{
513, 2052, 2054, 3080, 3082, 3084, 3086, 4112, 4114, 4116, 4118, 4120, 4122, 4124, 4126, 5152,
5154, 5156, 5158, 5160, 5162, 5164, 5166, 5168, 5170, 5172, 5174, 5176, 5178, 5180, 5182, 6208,
6210, 6212, 6214, 6216, 6218, 6220, 6222, 6224, 6226, 6228, 6230, 6232, 6234, 6236, 6238, 6240,
6242, 6244, 6246, 6248, 6250, 6252, 6254, 6256, 6258, 6260, 6262, 6264, 6266, 6268, 6270, 7296,
7298, 7300, 7302, 7304, 7306, 7308, 7310, 7312, 7314, 7316, 7318, 7320, 7322, 7324, 7326, 7328,
7330, 7332, 7334, 7336, 7338, 7340, 7342, 7344, 7346, 7348, 7350, 7352, 7354, 7356, 7358, 7360,
7362, 7364, 7366, 7368, 7370, 7372, 7374, 7376, 7378, 7380, 7382, 7384, 7386, 7388, 7390, 7392,
7394, 7396, 7398, 7400, 7402, 7404, 7406, 7408, 7410, 7412, 7414, 7416, 7418, 7420, 7422, 8448,
8451, 8449, 7423, 7421, 7419, 7417, 7415, 7413, 7411, 7409, 7407, 7405, 7403, 7401, 7399, 7397,
7395, 7393, 7391, 7389, 7387, 7385, 7383, 7381, 7379, 7377, 7375, 7373, 7371, 7369, 7367, 7365,
7363, 7361, 7359, 7357, 7355, 7353, 7351, 7349, 7347, 7345, 7343, 7341, 7339, 7337, 7335, 7333,
7331, 7329, 7327, 7325, 7323, 7321, 7319, 7317, 7315, 7313, 7311, 7309, 7307, 7305, 7303, 7301,
7299, 7297, 6271, 6269, 6267, 6265, 6263, 6261, 6259, 6257, 6255, 6253, 6251, 6249, 6247, 6245,
6243, 6241, 6239, 6237, 6235, 6233, 6231, 6229, 6227, 6225, 6223, 6221, 6219, 6217, 6215, 6213,
6211, 6209, 5183, 5181, 5179, 5177, 5175, 5173, 5171, 5169, 5167, 5165, 5163, 5161, 5159, 5157,
5155, 5153, 4127, 4125, 4123, 4121, 4119, 4117, 4115, 4113, 3087, 3085, 3083, 3081, 2055, 2053
}
};
private final int[] cache;
private final int signed; | // Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/ExpGolombEncoder.java
import kanzi.EntropyEncoder;
import kanzi.OutputBitStream;
6737, 6736, 6735, 6734, 6733, 6732, 6731, 6730, 6729, 6728, 6727, 6726, 6725, 6724, 6723, 6722,
6721, 6720, 5695, 5694, 5693, 5692, 5691, 5690, 5689, 5688, 5687, 5686, 5685, 5684, 5683, 5682,
5681, 5680, 5679, 5678, 5677, 5676, 5675, 5674, 5673, 5672, 5671, 5670, 5669, 5668, 5667, 5666,
5665, 5664, 4639, 4638, 4637, 4636, 4635, 4634, 4633, 4632, 4631, 4630, 4629, 4628, 4627, 4626,
4625, 4624, 3599, 3598, 3597, 3596, 3595, 3594, 3593, 3592, 2567, 2566, 2565, 2564, 1539, 1538
},
// Signed
new int[]
{
513, 2052, 2054, 3080, 3082, 3084, 3086, 4112, 4114, 4116, 4118, 4120, 4122, 4124, 4126, 5152,
5154, 5156, 5158, 5160, 5162, 5164, 5166, 5168, 5170, 5172, 5174, 5176, 5178, 5180, 5182, 6208,
6210, 6212, 6214, 6216, 6218, 6220, 6222, 6224, 6226, 6228, 6230, 6232, 6234, 6236, 6238, 6240,
6242, 6244, 6246, 6248, 6250, 6252, 6254, 6256, 6258, 6260, 6262, 6264, 6266, 6268, 6270, 7296,
7298, 7300, 7302, 7304, 7306, 7308, 7310, 7312, 7314, 7316, 7318, 7320, 7322, 7324, 7326, 7328,
7330, 7332, 7334, 7336, 7338, 7340, 7342, 7344, 7346, 7348, 7350, 7352, 7354, 7356, 7358, 7360,
7362, 7364, 7366, 7368, 7370, 7372, 7374, 7376, 7378, 7380, 7382, 7384, 7386, 7388, 7390, 7392,
7394, 7396, 7398, 7400, 7402, 7404, 7406, 7408, 7410, 7412, 7414, 7416, 7418, 7420, 7422, 8448,
8451, 8449, 7423, 7421, 7419, 7417, 7415, 7413, 7411, 7409, 7407, 7405, 7403, 7401, 7399, 7397,
7395, 7393, 7391, 7389, 7387, 7385, 7383, 7381, 7379, 7377, 7375, 7373, 7371, 7369, 7367, 7365,
7363, 7361, 7359, 7357, 7355, 7353, 7351, 7349, 7347, 7345, 7343, 7341, 7339, 7337, 7335, 7333,
7331, 7329, 7327, 7325, 7323, 7321, 7319, 7317, 7315, 7313, 7311, 7309, 7307, 7305, 7303, 7301,
7299, 7297, 6271, 6269, 6267, 6265, 6263, 6261, 6259, 6257, 6255, 6253, 6251, 6249, 6247, 6245,
6243, 6241, 6239, 6237, 6235, 6233, 6231, 6229, 6227, 6225, 6223, 6221, 6219, 6217, 6215, 6213,
6211, 6209, 5183, 5181, 5179, 5177, 5175, 5173, 5171, 5169, 5167, 5165, 5163, 5161, 5159, 5157,
5155, 5153, 4127, 4125, 4123, 4121, 4119, 4117, 4115, 4113, 3087, 3085, 3083, 3081, 2055, 2053
}
};
private final int[] cache;
private final int signed; | private final OutputBitStream bitstream; |
flanglet/kanzi | java/src/main/java/kanzi/entropy/EntropyCodecFactory.java | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import java.util.Map;
import kanzi.EntropyDecoder;
import kanzi.EntropyEncoder;
import kanzi.InputBitStream;
import kanzi.OutputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
public class EntropyCodecFactory
{
public static final byte NONE_TYPE = 0; // No compression
public static final byte HUFFMAN_TYPE = 1; // Huffman
public static final byte FPAQ_TYPE = 2; // Fast PAQ (order 0)
public static final byte PAQ_TYPE = 3; // Obsolete
public static final byte RANGE_TYPE = 4; // Range
public static final byte ANS0_TYPE = 5; // Asymmetric Numerical System order 0
public static final byte CM_TYPE = 6; // Context Model
public static final byte TPAQ_TYPE = 7; // Tangelo PAQ
public static final byte ANS1_TYPE = 8; // Asymmetric Numerical System order 1
public static final byte TPAQX_TYPE = 9; // Tangelo PAQ Extra
public static final byte RESERVED1 = 10; // Reserved
public static final byte RESERVED2 = 11; // Reserved
public static final byte RESERVED3 = 12; // Reserved
public static final byte RESERVED4 = 13; // Reserved
public static final byte RESERVED5 = 14; // Reserved
public static final byte RESERVED6 = 15; // Reserved
| // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/EntropyCodecFactory.java
import java.util.Map;
import kanzi.EntropyDecoder;
import kanzi.EntropyEncoder;
import kanzi.InputBitStream;
import kanzi.OutputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
public class EntropyCodecFactory
{
public static final byte NONE_TYPE = 0; // No compression
public static final byte HUFFMAN_TYPE = 1; // Huffman
public static final byte FPAQ_TYPE = 2; // Fast PAQ (order 0)
public static final byte PAQ_TYPE = 3; // Obsolete
public static final byte RANGE_TYPE = 4; // Range
public static final byte ANS0_TYPE = 5; // Asymmetric Numerical System order 0
public static final byte CM_TYPE = 6; // Context Model
public static final byte TPAQ_TYPE = 7; // Tangelo PAQ
public static final byte ANS1_TYPE = 8; // Asymmetric Numerical System order 1
public static final byte TPAQX_TYPE = 9; // Tangelo PAQ Extra
public static final byte RESERVED1 = 10; // Reserved
public static final byte RESERVED2 = 11; // Reserved
public static final byte RESERVED3 = 12; // Reserved
public static final byte RESERVED4 = 13; // Reserved
public static final byte RESERVED5 = 14; // Reserved
public static final byte RESERVED6 = 15; // Reserved
| public EntropyDecoder newDecoder(InputBitStream ibs, Map<String, Object> ctx, int entropyType) |
flanglet/kanzi | java/src/main/java/kanzi/entropy/EntropyCodecFactory.java | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import java.util.Map;
import kanzi.EntropyDecoder;
import kanzi.EntropyEncoder;
import kanzi.InputBitStream;
import kanzi.OutputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
public class EntropyCodecFactory
{
public static final byte NONE_TYPE = 0; // No compression
public static final byte HUFFMAN_TYPE = 1; // Huffman
public static final byte FPAQ_TYPE = 2; // Fast PAQ (order 0)
public static final byte PAQ_TYPE = 3; // Obsolete
public static final byte RANGE_TYPE = 4; // Range
public static final byte ANS0_TYPE = 5; // Asymmetric Numerical System order 0
public static final byte CM_TYPE = 6; // Context Model
public static final byte TPAQ_TYPE = 7; // Tangelo PAQ
public static final byte ANS1_TYPE = 8; // Asymmetric Numerical System order 1
public static final byte TPAQX_TYPE = 9; // Tangelo PAQ Extra
public static final byte RESERVED1 = 10; // Reserved
public static final byte RESERVED2 = 11; // Reserved
public static final byte RESERVED3 = 12; // Reserved
public static final byte RESERVED4 = 13; // Reserved
public static final byte RESERVED5 = 14; // Reserved
public static final byte RESERVED6 = 15; // Reserved
| // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/EntropyCodecFactory.java
import java.util.Map;
import kanzi.EntropyDecoder;
import kanzi.EntropyEncoder;
import kanzi.InputBitStream;
import kanzi.OutputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
public class EntropyCodecFactory
{
public static final byte NONE_TYPE = 0; // No compression
public static final byte HUFFMAN_TYPE = 1; // Huffman
public static final byte FPAQ_TYPE = 2; // Fast PAQ (order 0)
public static final byte PAQ_TYPE = 3; // Obsolete
public static final byte RANGE_TYPE = 4; // Range
public static final byte ANS0_TYPE = 5; // Asymmetric Numerical System order 0
public static final byte CM_TYPE = 6; // Context Model
public static final byte TPAQ_TYPE = 7; // Tangelo PAQ
public static final byte ANS1_TYPE = 8; // Asymmetric Numerical System order 1
public static final byte TPAQX_TYPE = 9; // Tangelo PAQ Extra
public static final byte RESERVED1 = 10; // Reserved
public static final byte RESERVED2 = 11; // Reserved
public static final byte RESERVED3 = 12; // Reserved
public static final byte RESERVED4 = 13; // Reserved
public static final byte RESERVED5 = 14; // Reserved
public static final byte RESERVED6 = 15; // Reserved
| public EntropyDecoder newDecoder(InputBitStream ibs, Map<String, Object> ctx, int entropyType) |
flanglet/kanzi | java/src/main/java/kanzi/entropy/EntropyCodecFactory.java | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import java.util.Map;
import kanzi.EntropyDecoder;
import kanzi.EntropyEncoder;
import kanzi.InputBitStream;
import kanzi.OutputBitStream; | case ANS0_TYPE:
return new ANSRangeDecoder(ibs, 0, ctx);
case ANS1_TYPE:
return new ANSRangeDecoder(ibs, 1, ctx);
case RANGE_TYPE:
return new RangeDecoder(ibs);
case FPAQ_TYPE:
return new FPAQDecoder(ibs);
case CM_TYPE:
return new BinaryEntropyDecoder(ibs, new CMPredictor());
case TPAQ_TYPE:
return new BinaryEntropyDecoder(ibs, new TPAQPredictor(ctx));
case TPAQX_TYPE:
return new BinaryEntropyDecoder(ibs, new TPAQPredictor(ctx));
case NONE_TYPE:
return new NullEntropyDecoder(ibs);
default:
throw new IllegalArgumentException("Unsupported entropy codec type: " + (char) entropyType);
}
}
| // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/EntropyCodecFactory.java
import java.util.Map;
import kanzi.EntropyDecoder;
import kanzi.EntropyEncoder;
import kanzi.InputBitStream;
import kanzi.OutputBitStream;
case ANS0_TYPE:
return new ANSRangeDecoder(ibs, 0, ctx);
case ANS1_TYPE:
return new ANSRangeDecoder(ibs, 1, ctx);
case RANGE_TYPE:
return new RangeDecoder(ibs);
case FPAQ_TYPE:
return new FPAQDecoder(ibs);
case CM_TYPE:
return new BinaryEntropyDecoder(ibs, new CMPredictor());
case TPAQ_TYPE:
return new BinaryEntropyDecoder(ibs, new TPAQPredictor(ctx));
case TPAQX_TYPE:
return new BinaryEntropyDecoder(ibs, new TPAQPredictor(ctx));
case NONE_TYPE:
return new NullEntropyDecoder(ibs);
default:
throw new IllegalArgumentException("Unsupported entropy codec type: " + (char) entropyType);
}
}
| public EntropyEncoder newEncoder(OutputBitStream obs, Map<String, Object> ctx, int entropyType) |
flanglet/kanzi | java/src/main/java/kanzi/entropy/EntropyCodecFactory.java | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import java.util.Map;
import kanzi.EntropyDecoder;
import kanzi.EntropyEncoder;
import kanzi.InputBitStream;
import kanzi.OutputBitStream; | case ANS0_TYPE:
return new ANSRangeDecoder(ibs, 0, ctx);
case ANS1_TYPE:
return new ANSRangeDecoder(ibs, 1, ctx);
case RANGE_TYPE:
return new RangeDecoder(ibs);
case FPAQ_TYPE:
return new FPAQDecoder(ibs);
case CM_TYPE:
return new BinaryEntropyDecoder(ibs, new CMPredictor());
case TPAQ_TYPE:
return new BinaryEntropyDecoder(ibs, new TPAQPredictor(ctx));
case TPAQX_TYPE:
return new BinaryEntropyDecoder(ibs, new TPAQPredictor(ctx));
case NONE_TYPE:
return new NullEntropyDecoder(ibs);
default:
throw new IllegalArgumentException("Unsupported entropy codec type: " + (char) entropyType);
}
}
| // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/EntropyCodecFactory.java
import java.util.Map;
import kanzi.EntropyDecoder;
import kanzi.EntropyEncoder;
import kanzi.InputBitStream;
import kanzi.OutputBitStream;
case ANS0_TYPE:
return new ANSRangeDecoder(ibs, 0, ctx);
case ANS1_TYPE:
return new ANSRangeDecoder(ibs, 1, ctx);
case RANGE_TYPE:
return new RangeDecoder(ibs);
case FPAQ_TYPE:
return new FPAQDecoder(ibs);
case CM_TYPE:
return new BinaryEntropyDecoder(ibs, new CMPredictor());
case TPAQ_TYPE:
return new BinaryEntropyDecoder(ibs, new TPAQPredictor(ctx));
case TPAQX_TYPE:
return new BinaryEntropyDecoder(ibs, new TPAQPredictor(ctx));
case NONE_TYPE:
return new NullEntropyDecoder(ibs);
default:
throw new IllegalArgumentException("Unsupported entropy codec type: " + (char) entropyType);
}
}
| public EntropyEncoder newEncoder(OutputBitStream obs, Map<String, Object> ctx, int entropyType) |
flanglet/kanzi | java/src/main/java/kanzi/transform/NullTransform.java | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
| import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
public class NullTransform implements ByteTransform
{
public NullTransform()
{
}
public NullTransform(Map<String, Object> ctx)
{
}
@Override | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
// Path: java/src/main/java/kanzi/transform/NullTransform.java
import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
public class NullTransform implements ByteTransform
{
public NullTransform()
{
}
public NullTransform(Map<String, Object> ctx)
{
}
@Override | public boolean forward(SliceByteArray input, SliceByteArray output) |
flanglet/kanzi | java/src/main/java/kanzi/entropy/ANSRangeDecoder.java | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
| import java.util.Map;
import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
import kanzi.InputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Implementation of an Asymmetric Numeral System decoder.
// See "Asymmetric Numeral System" by Jarek Duda at http://arxiv.org/abs/0902.0271
// Some code has been ported from https://github.com/rygorous/ryg_rans
// For an alternate C implementation example, see https://github.com/Cyan4973/FiniteStateEntropy
public class ANSRangeDecoder implements EntropyDecoder
{
private static final int ANS_TOP = 1 << 15; // max possible for ANS_TOP=1<23
private static final int DEFAULT_ANS0_CHUNK_SIZE = 1 << 15; // 32 KB by default
private static final int DEFAULT_LOG_RANGE = 12;
private static final int MIN_CHUNK_SIZE = 1024;
private static final int MAX_CHUNK_SIZE = 1 << 27; // 8*MAX_CHUNK_SIZE must not overflow
| // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
// Path: java/src/main/java/kanzi/entropy/ANSRangeDecoder.java
import java.util.Map;
import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
import kanzi.InputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Implementation of an Asymmetric Numeral System decoder.
// See "Asymmetric Numeral System" by Jarek Duda at http://arxiv.org/abs/0902.0271
// Some code has been ported from https://github.com/rygorous/ryg_rans
// For an alternate C implementation example, see https://github.com/Cyan4973/FiniteStateEntropy
public class ANSRangeDecoder implements EntropyDecoder
{
private static final int ANS_TOP = 1 << 15; // max possible for ANS_TOP=1<23
private static final int DEFAULT_ANS0_CHUNK_SIZE = 1 << 15; // 32 KB by default
private static final int DEFAULT_LOG_RANGE = 12;
private static final int MIN_CHUNK_SIZE = 1024;
private static final int MAX_CHUNK_SIZE = 1 << 27; // 8*MAX_CHUNK_SIZE must not overflow
| private final InputBitStream bitstream; |
flanglet/kanzi | java/src/main/java/kanzi/entropy/ANSRangeDecoder.java | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
| import java.util.Map;
import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
import kanzi.InputBitStream; | st3 = decodeSymbol(idx, st3, this.symbols[prv3][cur3], mask);
final int cur2 = this.f2s[prv2][st2&mask] & 0xFF;
block[i2] = (byte) cur2;
st2 = decodeSymbol(idx, st2, this.symbols[prv2][cur2], mask);
final int cur1 = this.f2s[prv1][st1&mask] & 0xFF;
block[i1] = (byte) cur1;
st1 = decodeSymbol(idx, st1, this.symbols[prv1][cur1], mask);
final int cur0 = this.f2s[prv0][st0&mask] & 0xFF;
block[i0] = (byte) cur0;
st0 = decodeSymbol(idx, st0, this.symbols[prv0][cur0], mask);
prv3 = cur3;
prv2 = cur2;
prv1 = cur1;
prv0 = cur0;
}
}
n = idx[0];
for (int i=end4; i<end; i++)
block[i] = this.buffer[n++];
}
// Decode alphabet and frequencies
protected int decodeHeader(int[][] frequencies, int[] alphabet)
{
this.logRange = (int) (8 + this.bitstream.readBits(3));
if ((this.logRange < 8) || (this.logRange > 16)) | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
// Path: java/src/main/java/kanzi/entropy/ANSRangeDecoder.java
import java.util.Map;
import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
import kanzi.InputBitStream;
st3 = decodeSymbol(idx, st3, this.symbols[prv3][cur3], mask);
final int cur2 = this.f2s[prv2][st2&mask] & 0xFF;
block[i2] = (byte) cur2;
st2 = decodeSymbol(idx, st2, this.symbols[prv2][cur2], mask);
final int cur1 = this.f2s[prv1][st1&mask] & 0xFF;
block[i1] = (byte) cur1;
st1 = decodeSymbol(idx, st1, this.symbols[prv1][cur1], mask);
final int cur0 = this.f2s[prv0][st0&mask] & 0xFF;
block[i0] = (byte) cur0;
st0 = decodeSymbol(idx, st0, this.symbols[prv0][cur0], mask);
prv3 = cur3;
prv2 = cur2;
prv1 = cur1;
prv0 = cur0;
}
}
n = idx[0];
for (int i=end4; i<end; i++)
block[i] = this.buffer[n++];
}
// Decode alphabet and frequencies
protected int decodeHeader(int[][] frequencies, int[] alphabet)
{
this.logRange = (int) (8 + this.bitstream.readBits(3));
if ((this.logRange < 8) || (this.logRange > 16)) | throw new BitStreamException("Invalid bitstream: range = "+this.logRange+ |
flanglet/kanzi | java/src/main/java/kanzi/entropy/RangeDecoder.java | // Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
| import kanzi.InputBitStream;
import kanzi.BitStreamException;
import kanzi.EntropyDecoder; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Based on Order 0 range coder by Dmitry Subbotin itself derived from the algorithm
// described by G.N.N Martin in his seminal article in 1979.
// [G.N.N. Martin on the Data Recording Conference, Southampton, 1979]
// Optimized for speed.
// Not thread safe
public final class RangeDecoder implements EntropyDecoder
{
private static final long TOP_RANGE = 0x0FFFFFFFFFFFFFFFL;
private static final long BOTTOM_RANGE = 0x000000000000FFFFL;
private static final long RANGE_MASK = 0x0FFFFFFF00000000L;
private static final int DEFAULT_CHUNK_SIZE = 1 << 15; // 32 KB by default
private static final int MAX_CHUNK_SIZE = 1 << 30;
private long code;
private long low;
private long range;
private final int[] alphabet;
private final int[] freqs;
private final long[] cumFreqs;
private short[] f2s; // mapping frequency -> symbol | // Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
// Path: java/src/main/java/kanzi/entropy/RangeDecoder.java
import kanzi.InputBitStream;
import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Based on Order 0 range coder by Dmitry Subbotin itself derived from the algorithm
// described by G.N.N Martin in his seminal article in 1979.
// [G.N.N. Martin on the Data Recording Conference, Southampton, 1979]
// Optimized for speed.
// Not thread safe
public final class RangeDecoder implements EntropyDecoder
{
private static final long TOP_RANGE = 0x0FFFFFFFFFFFFFFFL;
private static final long BOTTOM_RANGE = 0x000000000000FFFFL;
private static final long RANGE_MASK = 0x0FFFFFFF00000000L;
private static final int DEFAULT_CHUNK_SIZE = 1 << 15; // 32 KB by default
private static final int MAX_CHUNK_SIZE = 1 << 30;
private long code;
private long low;
private long range;
private final int[] alphabet;
private final int[] freqs;
private final long[] cumFreqs;
private short[] f2s; // mapping frequency -> symbol | private final InputBitStream bitstream; |
flanglet/kanzi | java/src/main/java/kanzi/entropy/RangeDecoder.java | // Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
| import kanzi.InputBitStream;
import kanzi.BitStreamException;
import kanzi.EntropyDecoder; | protected int decodeHeader(int[] frequencies)
{
int alphabetSize = EntropyUtils.decodeAlphabet(this.bitstream, this.alphabet);
if (alphabetSize == 0)
return 0;
if (alphabetSize != 256)
{
for (int i=0; i<256; i++)
frequencies[i] = 0;
}
final int logRange = (int) (8 + this.bitstream.readBits(3));
final int scale = 1 << logRange;
this.shift = logRange;
int sum = 0;
final int chkSize = (alphabetSize >= 64) ? 8 : 6;
int llr = 3;
while (1<<llr <= logRange)
llr++;
// Decode all frequencies (but the first one) by chunks of size 'inc'
for (int i=1; i<alphabetSize; i+=chkSize)
{
final int logMax = (int) this.bitstream.readBits(llr);
if (1<<logMax > scale)
{ | // Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
// Path: java/src/main/java/kanzi/entropy/RangeDecoder.java
import kanzi.InputBitStream;
import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
protected int decodeHeader(int[] frequencies)
{
int alphabetSize = EntropyUtils.decodeAlphabet(this.bitstream, this.alphabet);
if (alphabetSize == 0)
return 0;
if (alphabetSize != 256)
{
for (int i=0; i<256; i++)
frequencies[i] = 0;
}
final int logRange = (int) (8 + this.bitstream.readBits(3));
final int scale = 1 << logRange;
this.shift = logRange;
int sum = 0;
final int chkSize = (alphabetSize >= 64) ? 8 : 6;
int llr = 3;
while (1<<llr <= logRange)
llr++;
// Decode all frequencies (but the first one) by chunks of size 'inc'
for (int i=1; i<alphabetSize; i+=chkSize)
{
final int logMax = (int) this.bitstream.readBits(llr);
if (1<<logMax > scale)
{ | throw new BitStreamException("Invalid bitstream: incorrect frequency size " + |
flanglet/kanzi | java/src/main/java/kanzi/app/InfoPrinter.java | // Path: java/src/main/java/kanzi/Event.java
// public class Event
// {
// public enum Type
// {
// COMPRESSION_START,
// DECOMPRESSION_START,
// BEFORE_TRANSFORM,
// AFTER_TRANSFORM,
// BEFORE_ENTROPY,
// AFTER_ENTROPY,
// COMPRESSION_END,
// DECOMPRESSION_END,
// AFTER_HEADER_DECODING
// }
//
// private final int id;
// private final long size;
// private final int hash;
// private final Type type;
// private final boolean hashing;
// private final long time;
// private final String msg;
//
//
// public Event(Type type, int id, long size)
// {
// this(type, id, size, 0, false);
// }
//
//
// public Event(Type type, int id, String msg)
// {
// this(type, id, msg, 0);
// }
//
//
// public Event(Type type, int id, String msg, long time)
// {
// this.id = id;
// this.size = 0L;
// this.hash = 0;
// this.hashing = false;
// this.type = type;
// this.time = (time > 0) ? time : System.nanoTime();
// this.msg = msg;
// }
//
//
// public Event(Type type, int id, long size, int hash, boolean hashing)
// {
// this(type, id, size, hash, hashing, 0);
// }
//
//
// public Event(Type type, int id, long size, int hash, boolean hashing, long time)
// {
// this.id = id;
// this.size = size;
// this.hash = hash;
// this.hashing = hashing;
// this.type = type;
// this.time = (time > 0) ? time : System.nanoTime();
// this.msg = null;
// }
//
//
// public int getId()
// {
// return this.id;
// }
//
//
// public long getSize()
// {
// return this.size;
// }
//
//
// public long getTime()
// {
// return this.time;
// }
//
//
// public Integer getHash()
// {
// return (this.hashing == false) ? null : this.hash;
// }
//
//
// public Type getType()
// {
// return this.type;
// }
//
//
// @Override
// public String toString()
// {
// if (this.msg != null)
// return this.msg;
//
// StringBuilder sb = new StringBuilder(200);
// sb.append("{ \"type\":\"").append(this.getType()).append("\"");
//
// if (this.id >= 0)
// sb.append(", \"id\":").append(this.getId());
//
// sb.append(", \"size\":").append(this.getSize());
// sb.append(", \"time\":").append(this.getTime());
//
// if (this.hashing == true)
// sb.append(", \"hash\":").append(Integer.toHexString(this.getHash()));
//
// sb.append(" }");
// return sb.toString();
// }
// }
//
// Path: java/src/main/java/kanzi/Listener.java
// public interface Listener
// {
// public void processEvent(Event evt);
// }
| import kanzi.Event;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import kanzi.Listener; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.app;
// An implementation of Listener to display block information (verbose option
// of the BlockCompressor/BlockDecompressor)
public class InfoPrinter implements Listener
{
public enum Type { ENCODING, DECODING }
private final PrintStream ps;
private final Map<Integer, BlockInfo> map; | // Path: java/src/main/java/kanzi/Event.java
// public class Event
// {
// public enum Type
// {
// COMPRESSION_START,
// DECOMPRESSION_START,
// BEFORE_TRANSFORM,
// AFTER_TRANSFORM,
// BEFORE_ENTROPY,
// AFTER_ENTROPY,
// COMPRESSION_END,
// DECOMPRESSION_END,
// AFTER_HEADER_DECODING
// }
//
// private final int id;
// private final long size;
// private final int hash;
// private final Type type;
// private final boolean hashing;
// private final long time;
// private final String msg;
//
//
// public Event(Type type, int id, long size)
// {
// this(type, id, size, 0, false);
// }
//
//
// public Event(Type type, int id, String msg)
// {
// this(type, id, msg, 0);
// }
//
//
// public Event(Type type, int id, String msg, long time)
// {
// this.id = id;
// this.size = 0L;
// this.hash = 0;
// this.hashing = false;
// this.type = type;
// this.time = (time > 0) ? time : System.nanoTime();
// this.msg = msg;
// }
//
//
// public Event(Type type, int id, long size, int hash, boolean hashing)
// {
// this(type, id, size, hash, hashing, 0);
// }
//
//
// public Event(Type type, int id, long size, int hash, boolean hashing, long time)
// {
// this.id = id;
// this.size = size;
// this.hash = hash;
// this.hashing = hashing;
// this.type = type;
// this.time = (time > 0) ? time : System.nanoTime();
// this.msg = null;
// }
//
//
// public int getId()
// {
// return this.id;
// }
//
//
// public long getSize()
// {
// return this.size;
// }
//
//
// public long getTime()
// {
// return this.time;
// }
//
//
// public Integer getHash()
// {
// return (this.hashing == false) ? null : this.hash;
// }
//
//
// public Type getType()
// {
// return this.type;
// }
//
//
// @Override
// public String toString()
// {
// if (this.msg != null)
// return this.msg;
//
// StringBuilder sb = new StringBuilder(200);
// sb.append("{ \"type\":\"").append(this.getType()).append("\"");
//
// if (this.id >= 0)
// sb.append(", \"id\":").append(this.getId());
//
// sb.append(", \"size\":").append(this.getSize());
// sb.append(", \"time\":").append(this.getTime());
//
// if (this.hashing == true)
// sb.append(", \"hash\":").append(Integer.toHexString(this.getHash()));
//
// sb.append(" }");
// return sb.toString();
// }
// }
//
// Path: java/src/main/java/kanzi/Listener.java
// public interface Listener
// {
// public void processEvent(Event evt);
// }
// Path: java/src/main/java/kanzi/app/InfoPrinter.java
import kanzi.Event;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import kanzi.Listener;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.app;
// An implementation of Listener to display block information (verbose option
// of the BlockCompressor/BlockDecompressor)
public class InfoPrinter implements Listener
{
public enum Type { ENCODING, DECODING }
private final PrintStream ps;
private final Map<Integer, BlockInfo> map; | private final Event.Type[] thresholds; |
flanglet/kanzi | java/src/main/java/kanzi/transform/BWTS.java | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
| import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Bijective version of the Burrows-Wheeler Transform
// The main advantage over the regular BWT is that there is no need for a primary
// index (hence the bijectivity). BWTS is about 10% slower than BWT.
// Forward transform based on the code at https://code.google.com/p/mk-bwts/
// by Neal Burns and DivSufSort (port of libDivSufSort by Yuta Mori)
public class BWTS implements ByteTransform
{
private static final int MAX_BLOCK_SIZE = 1024*1024*1024; // 1 GB
private int[] buffer1;
private int[] buffer2;
private final int[] buckets;
private DivSufSort saAlgo;
public BWTS()
{
this.buffer1 = new int[0];
this.buffer2 = new int[0];
this.buckets = new int[256];
}
public BWTS(Map<String, Object> ctx)
{
this.buffer1 = new int[0];
this.buffer2 = new int[0];
this.buckets = new int[256];
}
// Not thread safe
@Override | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
// Path: java/src/main/java/kanzi/transform/BWTS.java
import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Bijective version of the Burrows-Wheeler Transform
// The main advantage over the regular BWT is that there is no need for a primary
// index (hence the bijectivity). BWTS is about 10% slower than BWT.
// Forward transform based on the code at https://code.google.com/p/mk-bwts/
// by Neal Burns and DivSufSort (port of libDivSufSort by Yuta Mori)
public class BWTS implements ByteTransform
{
private static final int MAX_BLOCK_SIZE = 1024*1024*1024; // 1 GB
private int[] buffer1;
private int[] buffer2;
private final int[] buckets;
private DivSufSort saAlgo;
public BWTS()
{
this.buffer1 = new int[0];
this.buffer2 = new int[0];
this.buckets = new int[256];
}
public BWTS(Map<String, Object> ctx)
{
this.buffer1 = new int[0];
this.buffer2 = new int[0];
this.buckets = new int[256];
}
// Not thread safe
@Override | public boolean forward(SliceByteArray src, SliceByteArray dst) |
flanglet/kanzi | java/src/main/java/kanzi/transform/Sequence.java | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
| import kanzi.ByteTransform;
import kanzi.SliceByteArray; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Encapsulates a sequence of transforms or functions in a function
public class Sequence implements ByteTransform
{
private static final byte SKIP_MASK = -1;
private final ByteTransform[] transforms; // transforms or functions
private byte skipFlags; // skip transforms
public Sequence(ByteTransform[] transforms)
{
if (transforms == null)
throw new NullPointerException("Invalid null transforms parameter");
if ((transforms.length == 0) || (transforms.length > 8))
throw new NullPointerException("Only 1 to 8 transforms allowed");
this.transforms = transforms;
}
@Override | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
// Path: java/src/main/java/kanzi/transform/Sequence.java
import kanzi.ByteTransform;
import kanzi.SliceByteArray;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Encapsulates a sequence of transforms or functions in a function
public class Sequence implements ByteTransform
{
private static final byte SKIP_MASK = -1;
private final ByteTransform[] transforms; // transforms or functions
private byte skipFlags; // skip transforms
public Sequence(ByteTransform[] transforms)
{
if (transforms == null)
throw new NullPointerException("Invalid null transforms parameter");
if ((transforms.length == 0) || (transforms.length > 8))
throw new NullPointerException("Only 1 to 8 transforms allowed");
this.transforms = transforms;
}
@Override | public boolean forward(SliceByteArray src, SliceByteArray dst) |
flanglet/kanzi | java/src/main/java/kanzi/bitstream/DebugInputBitStream.java | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
| import kanzi.BitStreamException;
import kanzi.InputBitStream;
import java.io.PrintStream; | {
return this.mark;
}
public synchronized void showByte(boolean hex)
{
this.hexa = hex;
}
public synchronized boolean showByte()
{
return this.hexa;
}
protected synchronized void printByte(byte val)
{
if ((val >= 0) && (val < 10))
this.out.print(" [00" + (val & 0xFF) + "] ");
else if ((val >= 0) && (val < 100))
this.out.print(" [0" + (val & 0xFF) + "] ");
else
this.out.print(" [" + (val & 0xFF) + "] ");
}
// Returns 1 or 0
@Override | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
// Path: java/src/main/java/kanzi/bitstream/DebugInputBitStream.java
import kanzi.BitStreamException;
import kanzi.InputBitStream;
import java.io.PrintStream;
{
return this.mark;
}
public synchronized void showByte(boolean hex)
{
this.hexa = hex;
}
public synchronized boolean showByte()
{
return this.hexa;
}
protected synchronized void printByte(byte val)
{
if ((val >= 0) && (val < 10))
this.out.print(" [00" + (val & 0xFF) + "] ");
else if ((val >= 0) && (val < 100))
this.out.print(" [0" + (val & 0xFF) + "] ");
else
this.out.print(" [" + (val & 0xFF) + "] ");
}
// Returns 1 or 0
@Override | public synchronized int readBit() throws BitStreamException |
flanglet/kanzi | java/src/main/java/kanzi/entropy/HuffmanDecoder.java | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
| import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
import kanzi.InputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Uses tables to decode symbols
public class HuffmanDecoder implements EntropyDecoder
{
private static final int DECODING_BATCH_SIZE = 14; // ensures decoding table fits in L1 cache
private static final int TABLE_MASK = (1<<DECODING_BATCH_SIZE) - 1;
| // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
// Path: java/src/main/java/kanzi/entropy/HuffmanDecoder.java
import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
import kanzi.InputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Uses tables to decode symbols
public class HuffmanDecoder implements EntropyDecoder
{
private static final int DECODING_BATCH_SIZE = 14; // ensures decoding table fits in L1 cache
private static final int TABLE_MASK = (1<<DECODING_BATCH_SIZE) - 1;
| private final InputBitStream bs; |
flanglet/kanzi | java/src/main/java/kanzi/entropy/HuffmanDecoder.java | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
| import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
import kanzi.InputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Uses tables to decode symbols
public class HuffmanDecoder implements EntropyDecoder
{
private static final int DECODING_BATCH_SIZE = 14; // ensures decoding table fits in L1 cache
private static final int TABLE_MASK = (1<<DECODING_BATCH_SIZE) - 1;
private final InputBitStream bs;
private final int[] codes;
private final int[] alphabet;
private final short[] sizes;
private final short[] table; // decoding table: code -> size, symbol
private final int chunkSize;
private long state; // holds bits read from bitstream
private int bits; // holds number of unused bits in 'state'
| // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
// Path: java/src/main/java/kanzi/entropy/HuffmanDecoder.java
import kanzi.BitStreamException;
import kanzi.EntropyDecoder;
import kanzi.InputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Uses tables to decode symbols
public class HuffmanDecoder implements EntropyDecoder
{
private static final int DECODING_BATCH_SIZE = 14; // ensures decoding table fits in L1 cache
private static final int TABLE_MASK = (1<<DECODING_BATCH_SIZE) - 1;
private final InputBitStream bs;
private final int[] codes;
private final int[] alphabet;
private final short[] sizes;
private final short[] table; // decoding table: code -> size, symbol
private final int chunkSize;
private long state; // holds bits read from bitstream
private int bits; // holds number of unused bits in 'state'
| public HuffmanDecoder(InputBitStream bitstream) throws BitStreamException |
flanglet/kanzi | java/src/main/java/kanzi/transform/SA_IS.java | // Path: java/src/main/java/kanzi/SliceIntArray.java
// public final class SliceIntArray
// {
// public int[] array; // array.length is the slice capacity
// public int index;
// public int length;
//
//
// public SliceIntArray()
// {
// this(new int[0], 0, 0);
// }
//
//
// public SliceIntArray(int[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceIntArray(int[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceIntArray sa = (SliceIntArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceIntArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
| import kanzi.SliceIntArray; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Compute suffix array using the SA_IS algorithm.
// This implementation is based on the SA_IS (Suffix Array Induction Sorting) algorithm.
// This is a port of sais.c by Yuta Mori (http://sites.google.com/site/yuta256/sais)
// See original publication of the algorithm here:
// [Ge Nong, Sen Zhang and Wai Hong Chan, Two Efficient Algorithms for
// Linear Suffix Array Construction, 2008]
// Another good read: http://labh-curien.univ-st-etienne.fr/~bellet/misc/SA_report.pdf
//
// Overview of the algorithm:
// Step 1 - Problem reduction: the input string is reduced into a smaller string.
// Step 2 - Recursion: the suffix array of the reduced problem is recursively computed.
// Step 3 - Problem induction: based on the suffix array of the reduced problem, that of the
// unreduced problem is induced
public class SA_IS
{
// find the start or end of each bucket | // Path: java/src/main/java/kanzi/SliceIntArray.java
// public final class SliceIntArray
// {
// public int[] array; // array.length is the slice capacity
// public int index;
// public int length;
//
//
// public SliceIntArray()
// {
// this(new int[0], 0, 0);
// }
//
//
// public SliceIntArray(int[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceIntArray(int[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceIntArray sa = (SliceIntArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceIntArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
// Path: java/src/main/java/kanzi/transform/SA_IS.java
import kanzi.SliceIntArray;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Compute suffix array using the SA_IS algorithm.
// This implementation is based on the SA_IS (Suffix Array Induction Sorting) algorithm.
// This is a port of sais.c by Yuta Mori (http://sites.google.com/site/yuta256/sais)
// See original publication of the algorithm here:
// [Ge Nong, Sen Zhang and Wai Hong Chan, Two Efficient Algorithms for
// Linear Suffix Array Construction, 2008]
// Another good read: http://labh-curien.univ-st-etienne.fr/~bellet/misc/SA_report.pdf
//
// Overview of the algorithm:
// Step 1 - Problem reduction: the input string is reduced into a smaller string.
// Step 2 - Recursion: the suffix array of the reduced problem is recursively computed.
// Step 3 - Problem induction: based on the suffix array of the reduced problem, that of the
// unreduced problem is induced
public class SA_IS
{
// find the start or end of each bucket | private static void getCounts(SliceIntArray src, SliceIntArray dst, int n, int k) |
flanglet/kanzi | java/src/main/java/kanzi/entropy/RiceGolombEncoder.java | // Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import kanzi.EntropyEncoder;
import kanzi.OutputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 Riceress or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kanzi.entropy;
public final class RiceGolombEncoder implements EntropyEncoder
{
private final boolean signed; | // Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/RiceGolombEncoder.java
import kanzi.EntropyEncoder;
import kanzi.OutputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 Riceress or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kanzi.entropy;
public final class RiceGolombEncoder implements EntropyEncoder
{
private final boolean signed; | private final OutputBitStream bitstream; |
flanglet/kanzi | java/src/main/java/kanzi/util/sort/QuickSort.java | // Path: java/src/main/java/kanzi/ArrayComparator.java
// public interface ArrayComparator
// {
// // Given an array (not provided here), return how the
// // sub-array starting at lidx compares to that starting at ridx
// public int compare(int lidx, int ridx);
// }
//
// Path: java/src/main/java/kanzi/IntSorter.java
// public interface IntSorter
// {
// public boolean sort(int[] array, int idx, int len);
// }
| import kanzi.ArrayComparator;
import kanzi.IntSorter; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.util.sort;
// Implementation of the Dual-Pivot Quicksort algorithm by
// Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch.
// See http://cr.openjdk.java.net/~alanb/DualPivotSortUpdate/webrev.01/raw_files/
// new/src/java.base/share/classes/java/util/DualPivotQuicksort.java
public class QuickSort implements IntSorter
{
private static final int HEAP_SORT_THRESHOLD = 69;
private static final int NANO_INSERTION_SORT_THRESHOLD = 36;
private static final int PAIR_INSERTION_SORT_THRESHOLD = 88;
private static final int MERGING_SORT_THRESHOLD = 2048;
private static final int MAX_RECURSION_DEPTH = 100;
private static final int LEFTMOST_BITS = MAX_RECURSION_DEPTH << 1;
| // Path: java/src/main/java/kanzi/ArrayComparator.java
// public interface ArrayComparator
// {
// // Given an array (not provided here), return how the
// // sub-array starting at lidx compares to that starting at ridx
// public int compare(int lidx, int ridx);
// }
//
// Path: java/src/main/java/kanzi/IntSorter.java
// public interface IntSorter
// {
// public boolean sort(int[] array, int idx, int len);
// }
// Path: java/src/main/java/kanzi/util/sort/QuickSort.java
import kanzi.ArrayComparator;
import kanzi.IntSorter;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.util.sort;
// Implementation of the Dual-Pivot Quicksort algorithm by
// Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch.
// See http://cr.openjdk.java.net/~alanb/DualPivotSortUpdate/webrev.01/raw_files/
// new/src/java.base/share/classes/java/util/DualPivotQuicksort.java
public class QuickSort implements IntSorter
{
private static final int HEAP_SORT_THRESHOLD = 69;
private static final int NANO_INSERTION_SORT_THRESHOLD = 36;
private static final int PAIR_INSERTION_SORT_THRESHOLD = 88;
private static final int MERGING_SORT_THRESHOLD = 2048;
private static final int MAX_RECURSION_DEPTH = 100;
private static final int LEFTMOST_BITS = MAX_RECURSION_DEPTH << 1;
| private final ArrayComparator cmp; |
flanglet/kanzi | java/src/main/java/kanzi/entropy/NullEntropyEncoder.java | // Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import kanzi.EntropyEncoder;
import kanzi.OutputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Null entropy encoder and decoder
// Pass through that writes the data directly to the bitstream
public final class NullEntropyEncoder implements EntropyEncoder
{ | // Path: java/src/main/java/kanzi/EntropyEncoder.java
// public interface EntropyEncoder
// {
// // Encode the array provided into the bitstream. Return the number of bytes
// // written to the bitstream
// public int encode(byte[] array, int blkptr, int len);
//
// // Return the underlying bitstream
// public OutputBitStream getBitStream();
//
// // Must be called before getting rid of the entropy coder
// // Trying to encode after a call to dispose gives undefined behavior
// public void dispose();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/NullEntropyEncoder.java
import kanzi.EntropyEncoder;
import kanzi.OutputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Null entropy encoder and decoder
// Pass through that writes the data directly to the bitstream
public final class NullEntropyEncoder implements EntropyEncoder
{ | private final OutputBitStream bitstream; |
flanglet/kanzi | java/src/test/java/kanzi/test/TestFlashSort.java | // Path: java/src/main/java/kanzi/util/sort/FlashSort.java
// public class FlashSort implements IntSorter
// {
// private static final int SHIFT = 15;
//
// private int[] buffer;
//
//
// public FlashSort()
// {
// this.buffer = new int[0];
// }
//
//
// // Not thread safe
// @Override
// public boolean sort(int[] input, int blkptr, int len)
// {
// if ((blkptr < 0) || (len <= 0) || (blkptr+len > input.length))
// return false;
//
// if (len == 1)
// return true;
//
// final int m = (len * 215) >> 9; // speed optimum m = 0.42 n
//
// if (this.buffer.length < m)
// this.buffer = new int[(m<32) ? 32 : (m+7) & -8];
//
// this.partialFlashSort(input, blkptr, len);
// return new InsertionSort().sort(input, blkptr, len);
// }
//
//
// private void partialFlashSort(int[] input, int blkptr, int count)
// {
// int min = input[blkptr];
// int max = min;
// int idxMax = blkptr;
// final int end = blkptr + count;
//
// for (int i=blkptr+1; i<end; i++)
// {
// int val = input[i];
//
// if (val < min)
// min = val;
//
// if (val > max)
// {
// max = val;
// idxMax = i;
// }
// }
//
// if (min == max)
// return;
//
// // Aliasing for speed
// final int[] buf = this.buffer;
// final int len8 = buf.length & -8;
// final long delta = max - min;
// final long delta1 = delta + 1;
//
// // Reset buckets buffer
// for (int i=0; i<len8; i+=8)
// {
// buf[i] = 0;
// buf[i+1] = 0;
// buf[i+2] = 0;
// buf[i+3] = 0;
// buf[i+4] = 0;
// buf[i+5] = 0;
// buf[i+6] = 0;
// buf[i+7] = 0;
// }
//
// int shiftL = SHIFT;
// final int threshold = Integer.MAX_VALUE >> 1;
// long c1 = 0;
// long num = 0;
//
// // Find combinations, shiftL, shiftR and c1
// while ((c1 == 0) && (num < threshold))
// {
// shiftL++;
// num = ((long) len8) << shiftL;
// c1 = num / delta1;
// }
//
// int shiftR = shiftL;
//
// while (c1 == 0)
// {
// final long denum = delta >>> (shiftR - shiftL);
// c1 = num / denum;
// shiftR++;
// }
//
// // Create the buckets
// for (int i=blkptr; i<end; i++)
// {
// final long k = (c1 * (input[i] - min)) >>> shiftR;
// buf[(int) k]++;
// }
//
// // Create distribution
// for (int i=1; i<len8; i++)
// buf[i] += buf[i-1];
//
// input[idxMax] = input[blkptr];
// input[blkptr] = max;
// int j = 0;
// int k = len8 - 1;
// int nmove = 1;
// final int offs = blkptr - 1;
//
// while (nmove < count)
// {
// while (j >= buf[k])
// {
// j++;
// final long kl = (c1 * (input[blkptr+j] - min)) >>> shiftR;
// k = (int) kl;
// }
//
// int flash = input[blkptr+j];
//
// // Speed critical section
// while (buf[k] != j)
// {
// final long kl = (c1 * (flash - min)) >>> shiftR;
// k = (int) kl;
// final int idx = offs + buf[k];
// final int hold = input[idx];
// input[idx] = flash;
// flash = hold;
// buf[k]--;
// nmove++;
// }
// }
// }
//
// }
| import kanzi.util.sort.FlashSort;
import org.junit.Assert;
import org.junit.Test; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.test;
public class TestFlashSort extends TestAbstractSort
{
@Test
public void testFlashSort()
{ | // Path: java/src/main/java/kanzi/util/sort/FlashSort.java
// public class FlashSort implements IntSorter
// {
// private static final int SHIFT = 15;
//
// private int[] buffer;
//
//
// public FlashSort()
// {
// this.buffer = new int[0];
// }
//
//
// // Not thread safe
// @Override
// public boolean sort(int[] input, int blkptr, int len)
// {
// if ((blkptr < 0) || (len <= 0) || (blkptr+len > input.length))
// return false;
//
// if (len == 1)
// return true;
//
// final int m = (len * 215) >> 9; // speed optimum m = 0.42 n
//
// if (this.buffer.length < m)
// this.buffer = new int[(m<32) ? 32 : (m+7) & -8];
//
// this.partialFlashSort(input, blkptr, len);
// return new InsertionSort().sort(input, blkptr, len);
// }
//
//
// private void partialFlashSort(int[] input, int blkptr, int count)
// {
// int min = input[blkptr];
// int max = min;
// int idxMax = blkptr;
// final int end = blkptr + count;
//
// for (int i=blkptr+1; i<end; i++)
// {
// int val = input[i];
//
// if (val < min)
// min = val;
//
// if (val > max)
// {
// max = val;
// idxMax = i;
// }
// }
//
// if (min == max)
// return;
//
// // Aliasing for speed
// final int[] buf = this.buffer;
// final int len8 = buf.length & -8;
// final long delta = max - min;
// final long delta1 = delta + 1;
//
// // Reset buckets buffer
// for (int i=0; i<len8; i+=8)
// {
// buf[i] = 0;
// buf[i+1] = 0;
// buf[i+2] = 0;
// buf[i+3] = 0;
// buf[i+4] = 0;
// buf[i+5] = 0;
// buf[i+6] = 0;
// buf[i+7] = 0;
// }
//
// int shiftL = SHIFT;
// final int threshold = Integer.MAX_VALUE >> 1;
// long c1 = 0;
// long num = 0;
//
// // Find combinations, shiftL, shiftR and c1
// while ((c1 == 0) && (num < threshold))
// {
// shiftL++;
// num = ((long) len8) << shiftL;
// c1 = num / delta1;
// }
//
// int shiftR = shiftL;
//
// while (c1 == 0)
// {
// final long denum = delta >>> (shiftR - shiftL);
// c1 = num / denum;
// shiftR++;
// }
//
// // Create the buckets
// for (int i=blkptr; i<end; i++)
// {
// final long k = (c1 * (input[i] - min)) >>> shiftR;
// buf[(int) k]++;
// }
//
// // Create distribution
// for (int i=1; i<len8; i++)
// buf[i] += buf[i-1];
//
// input[idxMax] = input[blkptr];
// input[blkptr] = max;
// int j = 0;
// int k = len8 - 1;
// int nmove = 1;
// final int offs = blkptr - 1;
//
// while (nmove < count)
// {
// while (j >= buf[k])
// {
// j++;
// final long kl = (c1 * (input[blkptr+j] - min)) >>> shiftR;
// k = (int) kl;
// }
//
// int flash = input[blkptr+j];
//
// // Speed critical section
// while (buf[k] != j)
// {
// final long kl = (c1 * (flash - min)) >>> shiftR;
// k = (int) kl;
// final int idx = offs + buf[k];
// final int hold = input[idx];
// input[idx] = flash;
// flash = hold;
// buf[k]--;
// nmove++;
// }
// }
// }
//
// }
// Path: java/src/test/java/kanzi/test/TestFlashSort.java
import kanzi.util.sort.FlashSort;
import org.junit.Assert;
import org.junit.Test;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.test;
public class TestFlashSort extends TestAbstractSort
{
@Test
public void testFlashSort()
{ | Assert.assertTrue(testCorrectness("FlashSort", new FlashSort(), 20)); |
flanglet/kanzi | java/src/main/java/kanzi/entropy/NullEntropyDecoder.java | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
| import kanzi.EntropyDecoder;
import kanzi.InputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Null entropy encoder and decoder
// Pass through that writes the data directly to the bitstream
public final class NullEntropyDecoder implements EntropyDecoder
{ | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
// Path: java/src/main/java/kanzi/entropy/NullEntropyDecoder.java
import kanzi.EntropyDecoder;
import kanzi.InputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Null entropy encoder and decoder
// Pass through that writes the data directly to the bitstream
public final class NullEntropyDecoder implements EntropyDecoder
{ | private final InputBitStream bitstream; |
flanglet/kanzi | java/src/main/java/kanzi/bitstream/DebugOutputBitStream.java | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import kanzi.BitStreamException;
import java.io.PrintStream;
import kanzi.OutputBitStream; | {
return this.mark;
}
public synchronized void showByte(boolean hex)
{
this.hexa = hex;
}
public synchronized boolean showByte()
{
return this.hexa;
}
protected synchronized void printByte(byte val)
{
if ((val >= 0) && (val < 10))
this.out.print(" [00" + (val & 0xFF) + "] ");
else if ((val >= 0) && (val < 100))
this.out.print(" [0" + (val & 0xFF) + "] ");
else
this.out.print(" [" + (val & 0xFF) + "] ");
}
// Processes the least significant bit of the input integer
@Override | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/bitstream/DebugOutputBitStream.java
import kanzi.BitStreamException;
import java.io.PrintStream;
import kanzi.OutputBitStream;
{
return this.mark;
}
public synchronized void showByte(boolean hex)
{
this.hexa = hex;
}
public synchronized boolean showByte()
{
return this.hexa;
}
protected synchronized void printByte(byte val)
{
if ((val >= 0) && (val < 10))
this.out.print(" [00" + (val & 0xFF) + "] ");
else if ((val >= 0) && (val < 100))
this.out.print(" [0" + (val & 0xFF) + "] ");
else
this.out.print(" [" + (val & 0xFF) + "] ");
}
// Processes the least significant bit of the input integer
@Override | public synchronized void writeBit(int bit) throws BitStreamException |
flanglet/kanzi | java/src/main/java/kanzi/entropy/ExpGolombDecoder.java | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
| import kanzi.EntropyDecoder;
import kanzi.InputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Exponential Golomb Coder
public final class ExpGolombDecoder implements EntropyDecoder
{
private final boolean signed; | // Path: java/src/main/java/kanzi/EntropyDecoder.java
// public interface EntropyDecoder
// {
// // Decode the next chunk of data from the bitstream and return in the
// // provided buffer.
// public int decode(byte[] buffer, int blkptr, int len);
//
// // Must be called before getting rid of the entropy coder
// public void dispose();
//
// // Return the underlying bitstream
// public InputBitStream getBitStream();
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
// Path: java/src/main/java/kanzi/entropy/ExpGolombDecoder.java
import kanzi.EntropyDecoder;
import kanzi.InputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// Exponential Golomb Coder
public final class ExpGolombDecoder implements EntropyDecoder
{
private final boolean signed; | private final InputBitStream bitstream; |
flanglet/kanzi | java/src/main/java/kanzi/util/sort/HeapSort.java | // Path: java/src/main/java/kanzi/ArrayComparator.java
// public interface ArrayComparator
// {
// // Given an array (not provided here), return how the
// // sub-array starting at lidx compares to that starting at ridx
// public int compare(int lidx, int ridx);
// }
//
// Path: java/src/main/java/kanzi/IntSorter.java
// public interface IntSorter
// {
// public boolean sort(int[] array, int idx, int len);
// }
| import kanzi.ArrayComparator;
import kanzi.IntSorter; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.util.sort;
// HeapSort is a comparison sort with O(n ln n) complexity. Practically, it is
// usually slower than QuickSort.
public final class HeapSort implements IntSorter
{ | // Path: java/src/main/java/kanzi/ArrayComparator.java
// public interface ArrayComparator
// {
// // Given an array (not provided here), return how the
// // sub-array starting at lidx compares to that starting at ridx
// public int compare(int lidx, int ridx);
// }
//
// Path: java/src/main/java/kanzi/IntSorter.java
// public interface IntSorter
// {
// public boolean sort(int[] array, int idx, int len);
// }
// Path: java/src/main/java/kanzi/util/sort/HeapSort.java
import kanzi.ArrayComparator;
import kanzi.IntSorter;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.util.sort;
// HeapSort is a comparison sort with O(n ln n) complexity. Practically, it is
// usually slower than QuickSort.
public final class HeapSort implements IntSorter
{ | private final ArrayComparator cmp; |
flanglet/kanzi | java/src/main/java/kanzi/util/sort/InsertionSort.java | // Path: java/src/main/java/kanzi/ArrayComparator.java
// public interface ArrayComparator
// {
// // Given an array (not provided here), return how the
// // sub-array starting at lidx compares to that starting at ridx
// public int compare(int lidx, int ridx);
// }
//
// Path: java/src/main/java/kanzi/IntSorter.java
// public interface IntSorter
// {
// public boolean sort(int[] array, int idx, int len);
// }
| import kanzi.ArrayComparator;
import kanzi.IntSorter; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.util.sort;
// Simple sorting algorithm with O(n*n) worst case complexity, O(n+k) on average
// Efficient on small data sets
public class InsertionSort implements IntSorter
{ | // Path: java/src/main/java/kanzi/ArrayComparator.java
// public interface ArrayComparator
// {
// // Given an array (not provided here), return how the
// // sub-array starting at lidx compares to that starting at ridx
// public int compare(int lidx, int ridx);
// }
//
// Path: java/src/main/java/kanzi/IntSorter.java
// public interface IntSorter
// {
// public boolean sort(int[] array, int idx, int len);
// }
// Path: java/src/main/java/kanzi/util/sort/InsertionSort.java
import kanzi.ArrayComparator;
import kanzi.IntSorter;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.util.sort;
// Simple sorting algorithm with O(n*n) worst case complexity, O(n+k) on average
// Efficient on small data sets
public class InsertionSort implements IntSorter
{ | private final ArrayComparator cmp; |
flanglet/kanzi | java/src/main/java/kanzi/transform/BWTBlockCodec.java | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
| import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Utility class to en/de-code a BWT data block and its associated primary index(es)
// BWT stream format: Header (m bytes) Data (n bytes)
// Header: For each primary index,
// mode (8 bits) + primary index (8,16 or 24 bits)
// mode: bits 7-6 contain the size in bits of the primary index :
// 00: primary index size <= 6 bits (fits in mode byte)
// 01: primary index size <= 14 bits (1 extra byte)
// 10: primary index size <= 22 bits (2 extra bytes)
// 11: primary index size > 22 bits (3 extra bytes)
// bits 5-0 contain 6 most significant bits of primary index
// primary index: remaining bits (up to 3 bytes)
public class BWTBlockCodec implements ByteTransform
{
private static final int BWT_MAX_HEADER_SIZE = 8 * 4;
private final BWT bwt;
public BWTBlockCodec()
{
this.bwt = new BWT();
}
public BWTBlockCodec(Map<String, Object> ctx)
{
this.bwt = new BWT(ctx);
}
// Return true if the compression chain succeeded. In this case, the input data
// may be modified. If the compression failed, the input data is returned unmodified.
@Override | // Path: java/src/main/java/kanzi/ByteTransform.java
// public interface ByteTransform
// {
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean forward(SliceByteArray src, SliceByteArray dst);
//
//
// // Read src.length bytes from src.array[src.index], process them and
// // write them to dst.array[dst.index]. The index of each slice is updated
// // with the number of bytes respectively read from and written to.
// public boolean inverse(SliceByteArray src, SliceByteArray dst);
//
//
// // Return the max size required for the output buffer
// public int getMaxEncodedLength(int srcLength);
// }
//
// Path: java/src/main/java/kanzi/SliceByteArray.java
// public final class SliceByteArray
// {
// public byte[] array; // array.length is the slice capacity
// public int length;
// public int index;
//
//
// public SliceByteArray()
// {
// this(new byte[0], 0, 0);
// }
//
//
// public SliceByteArray(byte[] array, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = array.length;
// this.index = idx;
// }
//
//
// public SliceByteArray(byte[] array, int length, int idx)
// {
// if (array == null)
// throw new NullPointerException("The array cannot be null");
//
// if (length < 0)
// throw new IllegalArgumentException("The length cannot be negative");
//
// if (idx < 0)
// throw new NullPointerException("The index cannot be negative");
//
// this.array = array;
// this.length = length;
// this.index = idx;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// try
// {
// if (o == null)
// return false;
//
// if (this == o)
// return true;
//
// SliceByteArray sa = (SliceByteArray) o;
// return ((this.array == sa.array) &&
// (this.length == sa.length) &&
// (this.index == sa.index));
// }
// catch (ClassCastException e)
// {
// return false;
// }
// }
//
//
// @Override
// public int hashCode()
// {
// return Objects.hashCode(this.array);
// }
//
//
// @Override
// @SuppressWarnings("lgtm [java/print-array]")
// public String toString()
// {
// StringBuilder builder = new StringBuilder(100);
// builder.append("[ data=");
// builder.append(String.valueOf(this.array));
// builder.append(", len=");
// builder.append(this.length);
// builder.append(", idx=");
// builder.append(this.index);
// builder.append("]");
// return builder.toString();
// }
//
//
// public static boolean isValid(SliceByteArray sa)
// {
// if (sa == null)
// return false;
//
// if (sa.array == null)
// return false;
//
// if (sa.index < 0)
// return false;
//
// if (sa.length < 0)
// return false;
//
// return (sa.index <= sa.array.length);
// }
// }
// Path: java/src/main/java/kanzi/transform/BWTBlockCodec.java
import java.util.Map;
import kanzi.ByteTransform;
import kanzi.SliceByteArray;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.transform;
// Utility class to en/de-code a BWT data block and its associated primary index(es)
// BWT stream format: Header (m bytes) Data (n bytes)
// Header: For each primary index,
// mode (8 bits) + primary index (8,16 or 24 bits)
// mode: bits 7-6 contain the size in bits of the primary index :
// 00: primary index size <= 6 bits (fits in mode byte)
// 01: primary index size <= 14 bits (1 extra byte)
// 10: primary index size <= 22 bits (2 extra bytes)
// 11: primary index size > 22 bits (3 extra bytes)
// bits 5-0 contain 6 most significant bits of primary index
// primary index: remaining bits (up to 3 bytes)
public class BWTBlockCodec implements ByteTransform
{
private static final int BWT_MAX_HEADER_SIZE = 8 * 4;
private final BWT bwt;
public BWTBlockCodec()
{
this.bwt = new BWT();
}
public BWTBlockCodec(Map<String, Object> ctx)
{
this.bwt = new BWT(ctx);
}
// Return true if the compression chain succeeded. In this case, the input data
// may be modified. If the compression failed, the input data is returned unmodified.
@Override | public boolean forward(SliceByteArray input, SliceByteArray output) |
flanglet/kanzi | java/src/main/java/kanzi/entropy/EntropyUtils.java | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import kanzi.BitStreamException;
import kanzi.InputBitStream;
import kanzi.OutputBitStream; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
public class EntropyUtils
{
public static final int INCOMPRESSIBLE_THRESHOLD = 973; // 0.95*1024
private static final int FULL_ALPHABET = 0;
private static final int PARTIAL_ALPHABET = 1;
private static final int ALPHABET_256 = 0;
private static final int ALPHABET_0 = 1;
// alphabet must be sorted in increasing order
// alphabet length must be a power of 2 up to 256 | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/EntropyUtils.java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import kanzi.BitStreamException;
import kanzi.InputBitStream;
import kanzi.OutputBitStream;
/*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
public class EntropyUtils
{
public static final int INCOMPRESSIBLE_THRESHOLD = 973; // 0.95*1024
private static final int FULL_ALPHABET = 0;
private static final int PARTIAL_ALPHABET = 1;
private static final int ALPHABET_256 = 0;
private static final int ALPHABET_0 = 1;
// alphabet must be sorted in increasing order
// alphabet length must be a power of 2 up to 256 | public static int encodeAlphabet(OutputBitStream obs, int[] alphabet, int count) |
flanglet/kanzi | java/src/main/java/kanzi/entropy/EntropyUtils.java | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import kanzi.BitStreamException;
import kanzi.InputBitStream;
import kanzi.OutputBitStream; | obs.writeBit(FULL_ALPHABET);
obs.writeBit(ALPHABET_0);
break;
case 256:
obs.writeBit(FULL_ALPHABET);
obs.writeBit(ALPHABET_256);
break;
default:
// Partial alphabet
obs.writeBit(PARTIAL_ALPHABET);
byte[] masks = new byte[32];
for (int i=0; i<count; i++)
masks[alphabet[i]>>3] |= (1 << (alphabet[i]&7));
final int lastMask = alphabet[count-1] >> 3;
obs.writeBits(lastMask, 5);
for (int i=0; i<=lastMask; i++)
obs.writeBits(masks[i], 8);
break;
}
return count;
}
| // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/EntropyUtils.java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import kanzi.BitStreamException;
import kanzi.InputBitStream;
import kanzi.OutputBitStream;
obs.writeBit(FULL_ALPHABET);
obs.writeBit(ALPHABET_0);
break;
case 256:
obs.writeBit(FULL_ALPHABET);
obs.writeBit(ALPHABET_256);
break;
default:
// Partial alphabet
obs.writeBit(PARTIAL_ALPHABET);
byte[] masks = new byte[32];
for (int i=0; i<count; i++)
masks[alphabet[i]>>3] |= (1 << (alphabet[i]&7));
final int lastMask = alphabet[count-1] >> 3;
obs.writeBits(lastMask, 5);
for (int i=0; i<=lastMask; i++)
obs.writeBits(masks[i], 8);
break;
}
return count;
}
| public static int decodeAlphabet(InputBitStream ibs, int[] alphabet) throws BitStreamException |
flanglet/kanzi | java/src/main/java/kanzi/entropy/EntropyUtils.java | // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
| import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import kanzi.BitStreamException;
import kanzi.InputBitStream;
import kanzi.OutputBitStream; | obs.writeBit(FULL_ALPHABET);
obs.writeBit(ALPHABET_0);
break;
case 256:
obs.writeBit(FULL_ALPHABET);
obs.writeBit(ALPHABET_256);
break;
default:
// Partial alphabet
obs.writeBit(PARTIAL_ALPHABET);
byte[] masks = new byte[32];
for (int i=0; i<count; i++)
masks[alphabet[i]>>3] |= (1 << (alphabet[i]&7));
final int lastMask = alphabet[count-1] >> 3;
obs.writeBits(lastMask, 5);
for (int i=0; i<=lastMask; i++)
obs.writeBits(masks[i], 8);
break;
}
return count;
}
| // Path: java/src/main/java/kanzi/BitStreamException.java
// public class BitStreamException extends RuntimeException
// {
// private static final long serialVersionUID = 7279737120722476336L;
//
// public static final int UNDEFINED = 0;
// public static final int INPUT_OUTPUT = 1;
// public static final int END_OF_STREAM = 2;
// public static final int INVALID_STREAM = 3;
// public static final int STREAM_CLOSED = 4;
//
// private final int code;
//
//
// protected BitStreamException()
// {
// this.code = UNDEFINED;
// }
//
//
// public BitStreamException(String message, int code)
// {
// super(message);
// this.code = code;
// }
//
//
// public BitStreamException(String message, Throwable cause, int code)
// {
// super(message, cause);
// this.code = code;
// }
//
//
// public BitStreamException(Throwable cause, int code)
// {
// super(cause);
// this.code = code;
// }
//
//
// public int getErrorCode()
// {
// return this.code;
// }
// }
//
// Path: java/src/main/java/kanzi/InputBitStream.java
// public interface InputBitStream
// {
// // Return 1 or 0
// public int readBit() throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the bits read as a long
// // Throws if the stream is closed.
// public long readBits(int length) throws BitStreamException;
//
// // Read bits and put them in the byte array at index 'start'.
// // Length is the number of bits
// // Return the number of bits read.
// // Throws if the stream is closed.
// public int readBits(byte[] bits, int start, int length) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits read
// public long read();
//
// // Return false when the bitstream is closed or the End-Of-Stream has been reached
// public boolean hasMoreToRead();
// }
//
// Path: java/src/main/java/kanzi/OutputBitStream.java
// public interface OutputBitStream
// {
// // Write the least significant bit of the input integer
// // Throws if the stream is closed.
// public void writeBit(int bit) throws BitStreamException;
//
// // Length is the number of bits in [1..64]. Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(long bits, int length) throws BitStreamException;
//
// // Write bits ouf of the byte array at index 'start'.
// // Length is the number of bits.
// // Return the number of bits written.
// // Throws if the stream is closed.
// public int writeBits(byte[] bits, int start, int nbBits) throws BitStreamException;
//
// public void close() throws BitStreamException;
//
// // Number of bits written
// public long written();
// }
// Path: java/src/main/java/kanzi/entropy/EntropyUtils.java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import kanzi.BitStreamException;
import kanzi.InputBitStream;
import kanzi.OutputBitStream;
obs.writeBit(FULL_ALPHABET);
obs.writeBit(ALPHABET_0);
break;
case 256:
obs.writeBit(FULL_ALPHABET);
obs.writeBit(ALPHABET_256);
break;
default:
// Partial alphabet
obs.writeBit(PARTIAL_ALPHABET);
byte[] masks = new byte[32];
for (int i=0; i<count; i++)
masks[alphabet[i]>>3] |= (1 << (alphabet[i]&7));
final int lastMask = alphabet[count-1] >> 3;
obs.writeBits(lastMask, 5);
for (int i=0; i<=lastMask; i++)
obs.writeBits(masks[i], 8);
break;
}
return count;
}
| public static int decodeAlphabet(InputBitStream ibs, int[] alphabet) throws BitStreamException |
fredokun/yaw | src/java/yaw/engine/meshs/MeshBuilder.java | // Path: src/java/yaw/engine/meshs/strategy/BoundingBoxDrawingStrategy.java
// public class BoundingBoxDrawingStrategy implements MeshDrawingStrategy {
//
// @Override
// public void drawMesh(Mesh pMesh) {
// glEnable(GL_POLYGON_OFFSET_FILL);
// glEnable(GL_PROGRAM_POINT_SIZE);
// glPolygonOffset(1, 0);
// glDrawElements(GL_LINES, pMesh.getIndices().length, GL_UNSIGNED_INT, 0);
// }
// }
//
// Path: src/java/yaw/engine/meshs/strategy/DefaultDrawingStrategy.java
// public class DefaultDrawingStrategy implements MeshDrawingStrategy {
//
//
// @Override
// public void drawMesh(Mesh pMesh) {
// // Draw the mVertices
// glDrawElements(GL_TRIANGLES, pMesh.getIndices().length, GL_UNSIGNED_INT, 0);
// }
//
// }
| import yaw.engine.meshs.strategy.BoundingBoxDrawingStrategy;
import org.joml.Vector3f;
import yaw.engine.meshs.strategy.DefaultDrawingStrategy;
import java.util.HashMap;
import java.util.Map; |
// For text coords in right face
0.0f, 0.0f,
0.0f, 0.5f,
// For text coords in left face
0.5f, 0.0f,
0.5f, 0.5f,
// For text coords in bottom face
0.5f, 0.0f,
1.0f, 0.0f,
0.5f, 0.5f,
1.0f, 0.5f,
};
//mapping the triangle for each face
int[] indices = new int[]{
//Front face
0, 1, 2, 0, 2, 3,
//Top face
4, 6, 5, 6, 7, 5,
//Back face
8, 11, 10, 8, 10, 9,
//Bottom Face
14, 12, 13, 14, 13, 15,
//Left face
16, 19, 18, 16, 17, 19,
//Right face
20, 22, 21, 22, 23, 21};
Mesh lMesh = new Mesh(vertices, textCoord, normals, indices, 8); | // Path: src/java/yaw/engine/meshs/strategy/BoundingBoxDrawingStrategy.java
// public class BoundingBoxDrawingStrategy implements MeshDrawingStrategy {
//
// @Override
// public void drawMesh(Mesh pMesh) {
// glEnable(GL_POLYGON_OFFSET_FILL);
// glEnable(GL_PROGRAM_POINT_SIZE);
// glPolygonOffset(1, 0);
// glDrawElements(GL_LINES, pMesh.getIndices().length, GL_UNSIGNED_INT, 0);
// }
// }
//
// Path: src/java/yaw/engine/meshs/strategy/DefaultDrawingStrategy.java
// public class DefaultDrawingStrategy implements MeshDrawingStrategy {
//
//
// @Override
// public void drawMesh(Mesh pMesh) {
// // Draw the mVertices
// glDrawElements(GL_TRIANGLES, pMesh.getIndices().length, GL_UNSIGNED_INT, 0);
// }
//
// }
// Path: src/java/yaw/engine/meshs/MeshBuilder.java
import yaw.engine.meshs.strategy.BoundingBoxDrawingStrategy;
import org.joml.Vector3f;
import yaw.engine.meshs.strategy.DefaultDrawingStrategy;
import java.util.HashMap;
import java.util.Map;
// For text coords in right face
0.0f, 0.0f,
0.0f, 0.5f,
// For text coords in left face
0.5f, 0.0f,
0.5f, 0.5f,
// For text coords in bottom face
0.5f, 0.0f,
1.0f, 0.0f,
0.5f, 0.5f,
1.0f, 0.5f,
};
//mapping the triangle for each face
int[] indices = new int[]{
//Front face
0, 1, 2, 0, 2, 3,
//Top face
4, 6, 5, 6, 7, 5,
//Back face
8, 11, 10, 8, 10, 9,
//Bottom Face
14, 12, 13, 14, 13, 15,
//Left face
16, 19, 18, 16, 17, 19,
//Right face
20, 22, 21, 22, 23, 21};
Mesh lMesh = new Mesh(vertices, textCoord, normals, indices, 8); | lMesh.setDrawingStrategy(new DefaultDrawingStrategy()); |
fredokun/yaw | src/java/yaw/engine/meshs/MeshBuilder.java | // Path: src/java/yaw/engine/meshs/strategy/BoundingBoxDrawingStrategy.java
// public class BoundingBoxDrawingStrategy implements MeshDrawingStrategy {
//
// @Override
// public void drawMesh(Mesh pMesh) {
// glEnable(GL_POLYGON_OFFSET_FILL);
// glEnable(GL_PROGRAM_POINT_SIZE);
// glPolygonOffset(1, 0);
// glDrawElements(GL_LINES, pMesh.getIndices().length, GL_UNSIGNED_INT, 0);
// }
// }
//
// Path: src/java/yaw/engine/meshs/strategy/DefaultDrawingStrategy.java
// public class DefaultDrawingStrategy implements MeshDrawingStrategy {
//
//
// @Override
// public void drawMesh(Mesh pMesh) {
// // Draw the mVertices
// glDrawElements(GL_TRIANGLES, pMesh.getIndices().length, GL_UNSIGNED_INT, 0);
// }
//
// }
| import yaw.engine.meshs.strategy.BoundingBoxDrawingStrategy;
import org.joml.Vector3f;
import yaw.engine.meshs.strategy.DefaultDrawingStrategy;
import java.util.HashMap;
import java.util.Map; | float x = xLength / 2f;
float y = yLength / 2f;
float z = zLength / 2f;
float[] vertices = new float[]{
//Front face
x, y, z, -x, y, z, -x, -y, z, x, -y, z,
//Top face
x, y, z, -x, y, z, x, y, -z, -x, y, -z,
//Back face
x, y, -z, -x, y, -z, -x, -y, -z, x, -y, -z,
//Bottom face
x, -y, z, -x, -y, z, x, -y, -z, -x, -y, -z,
//Left face
-x, y, z, -x, y, -z, -x, -y, z, -x, -y, -z,
//Right face
x, y, z, x, y, -z, x, -y, z, x, -y, -z};
float[] normals = {0};
float[] textCoord = {0};
int[] indices = new int[]{
//Front face
0, 1, 1, 2, 2, 3, 3, 0,
//Top face
0, 8, 9, 1, 2, 10, 3, 11,
//Back face
8, 9, 9, 10, 10, 11, 11, 8};
Mesh lMesh = new Mesh(vertices, textCoord, normals, indices);
//we set the new strategy | // Path: src/java/yaw/engine/meshs/strategy/BoundingBoxDrawingStrategy.java
// public class BoundingBoxDrawingStrategy implements MeshDrawingStrategy {
//
// @Override
// public void drawMesh(Mesh pMesh) {
// glEnable(GL_POLYGON_OFFSET_FILL);
// glEnable(GL_PROGRAM_POINT_SIZE);
// glPolygonOffset(1, 0);
// glDrawElements(GL_LINES, pMesh.getIndices().length, GL_UNSIGNED_INT, 0);
// }
// }
//
// Path: src/java/yaw/engine/meshs/strategy/DefaultDrawingStrategy.java
// public class DefaultDrawingStrategy implements MeshDrawingStrategy {
//
//
// @Override
// public void drawMesh(Mesh pMesh) {
// // Draw the mVertices
// glDrawElements(GL_TRIANGLES, pMesh.getIndices().length, GL_UNSIGNED_INT, 0);
// }
//
// }
// Path: src/java/yaw/engine/meshs/MeshBuilder.java
import yaw.engine.meshs.strategy.BoundingBoxDrawingStrategy;
import org.joml.Vector3f;
import yaw.engine.meshs.strategy.DefaultDrawingStrategy;
import java.util.HashMap;
import java.util.Map;
float x = xLength / 2f;
float y = yLength / 2f;
float z = zLength / 2f;
float[] vertices = new float[]{
//Front face
x, y, z, -x, y, z, -x, -y, z, x, -y, z,
//Top face
x, y, z, -x, y, z, x, y, -z, -x, y, -z,
//Back face
x, y, -z, -x, y, -z, -x, -y, -z, x, -y, -z,
//Bottom face
x, -y, z, -x, -y, z, x, -y, -z, -x, -y, -z,
//Left face
-x, y, z, -x, y, -z, -x, -y, z, -x, -y, -z,
//Right face
x, y, z, x, y, -z, x, -y, z, x, -y, -z};
float[] normals = {0};
float[] textCoord = {0};
int[] indices = new int[]{
//Front face
0, 1, 1, 2, 2, 3, 3, 0,
//Top face
0, 8, 9, 1, 2, 10, 3, 11,
//Back face
8, 9, 9, 10, 10, 11, 11, 8};
Mesh lMesh = new Mesh(vertices, textCoord, normals, indices);
//we set the new strategy | lMesh.setDrawingStrategy(new BoundingBoxDrawingStrategy()); |
sgoeschl/java-image-processing-survival-guide | code/jipsg/twelvemonkeys/src/test/java/org/github/jipsg/twelvemonkeys/BaseTwelveMonkeysTest.java | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/AbstractImageTest.java
// public abstract class AbstractImageTest {
//
// private String moduleName;
// private File imageDirectory;
//
// public abstract BufferedImage createBufferedImage(final File file) throws Exception;
//
// public abstract void writeBufferedImage(final BufferedImage bufferedImage, final String formatName, final File file) throws Exception;
//
// public abstract BufferedImage resample(final BufferedImage bufferedImage, int width, int height);
//
// public abstract void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception;
//
// public void setup() {
// File currDirectory = new File("");
// if (currDirectory.getAbsolutePath().endsWith("jipsg")) {
// this.imageDirectory = new File("../images");
// } else {
// this.imageDirectory = new File("../../images");
// }
// }
//
// protected void setModuleName(String moduleName) {
// this.moduleName = moduleName;
// }
//
// /**
// * Get the given file.
// *
// * @param folderName Name of the folder under "images"
// * @param fileName File name
// * @return the file
// */
// protected File getImageFile(String folderName, String fileName) throws IOException {
// File folderFile = new File(getImageDirectory(), folderName);
// File result = new File(folderFile, fileName);
// if (!result.exists() || !result.canRead()) {
// throw new IOException("Can't open/read the following file : " + result.getAbsolutePath());
// }
// return result;
// }
//
// /**
// * Some dumb sanity check that we have a valid buffered image.
// */
// protected void assertValidBufferedImage(BufferedImage bufferedImage) {
// assertNotNull("bufferedImage is null", bufferedImage);
// assertTrue(bufferedImage.getHeight() > 0);
// assertTrue(bufferedImage.getWidth() > 0);
// }
//
// protected File createOutputFileName(String directory, File file, String format) {
// return createOutputFileName(directory, file.getName(), format);
// }
//
// protected File createOutputFileName(String directory, String fileName, String format) {
//
// File outputDir = new File(new File(new File(new File("./target"), "out"), this.moduleName), directory);
//
// if (!outputDir.exists()) {
// outputDir.mkdirs();
// }
//
// return new File(outputDir, fileName + "." + format);
// }
//
// private File getImageDirectory() {
// return imageDirectory;
// }
// }
//
// Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageUtils.java
// public class BufferedImageUtils {
//
// public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
//
// int original_width = imgSize.width;
// int original_height = imgSize.height;
// int bound_width = boundary.width;
// int bound_height = boundary.height;
// int new_width = original_width;
// int new_height = original_height;
//
// // first check if we need to scale width
// if (original_width > bound_width) {
// //scale width to fit
// new_width = bound_width;
// //scale height to maintain aspect ratio
// new_height = (new_width * original_height) / original_width;
// }
//
// // then check if we need to scale even with the new height
// if (new_height > bound_height) {
// //scale height to fit instead
// new_height = bound_height;
// //scale width to maintain aspect ratio
// new_width = (new_height * original_width) / original_height;
// }
//
// return new Dimension(new_width, new_height);
// }
// }
| import com.twelvemonkeys.image.ResampleOp;
import org.github.jipsg.common.AbstractImageTest;
import org.github.jipsg.common.image.BufferedImageUtils;
import javax.imageio.ImageIO;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.github.jipsg.twelvemonkeys;
/**
* Base class for testing TwelveMonkey library.
*/
public class BaseTwelveMonkeysTest extends AbstractImageTest {
@Override
public void setup() {
super.setModuleName("twelvemonkeys");
super.setup();
}
@Override
public BufferedImage createBufferedImage(File file) throws Exception {
return ImageIO.read(file);
}
@Override
public void writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
System.out.println("Saving " + file.getPath());
ImageIO.write(bufferedImage, formatName, file);
}
@Override
public void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
Dimension boundaryDimension = new Dimension(width, height); | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/AbstractImageTest.java
// public abstract class AbstractImageTest {
//
// private String moduleName;
// private File imageDirectory;
//
// public abstract BufferedImage createBufferedImage(final File file) throws Exception;
//
// public abstract void writeBufferedImage(final BufferedImage bufferedImage, final String formatName, final File file) throws Exception;
//
// public abstract BufferedImage resample(final BufferedImage bufferedImage, int width, int height);
//
// public abstract void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception;
//
// public void setup() {
// File currDirectory = new File("");
// if (currDirectory.getAbsolutePath().endsWith("jipsg")) {
// this.imageDirectory = new File("../images");
// } else {
// this.imageDirectory = new File("../../images");
// }
// }
//
// protected void setModuleName(String moduleName) {
// this.moduleName = moduleName;
// }
//
// /**
// * Get the given file.
// *
// * @param folderName Name of the folder under "images"
// * @param fileName File name
// * @return the file
// */
// protected File getImageFile(String folderName, String fileName) throws IOException {
// File folderFile = new File(getImageDirectory(), folderName);
// File result = new File(folderFile, fileName);
// if (!result.exists() || !result.canRead()) {
// throw new IOException("Can't open/read the following file : " + result.getAbsolutePath());
// }
// return result;
// }
//
// /**
// * Some dumb sanity check that we have a valid buffered image.
// */
// protected void assertValidBufferedImage(BufferedImage bufferedImage) {
// assertNotNull("bufferedImage is null", bufferedImage);
// assertTrue(bufferedImage.getHeight() > 0);
// assertTrue(bufferedImage.getWidth() > 0);
// }
//
// protected File createOutputFileName(String directory, File file, String format) {
// return createOutputFileName(directory, file.getName(), format);
// }
//
// protected File createOutputFileName(String directory, String fileName, String format) {
//
// File outputDir = new File(new File(new File(new File("./target"), "out"), this.moduleName), directory);
//
// if (!outputDir.exists()) {
// outputDir.mkdirs();
// }
//
// return new File(outputDir, fileName + "." + format);
// }
//
// private File getImageDirectory() {
// return imageDirectory;
// }
// }
//
// Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageUtils.java
// public class BufferedImageUtils {
//
// public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
//
// int original_width = imgSize.width;
// int original_height = imgSize.height;
// int bound_width = boundary.width;
// int bound_height = boundary.height;
// int new_width = original_width;
// int new_height = original_height;
//
// // first check if we need to scale width
// if (original_width > bound_width) {
// //scale width to fit
// new_width = bound_width;
// //scale height to maintain aspect ratio
// new_height = (new_width * original_height) / original_width;
// }
//
// // then check if we need to scale even with the new height
// if (new_height > bound_height) {
// //scale height to fit instead
// new_height = bound_height;
// //scale width to maintain aspect ratio
// new_width = (new_height * original_width) / original_height;
// }
//
// return new Dimension(new_width, new_height);
// }
// }
// Path: code/jipsg/twelvemonkeys/src/test/java/org/github/jipsg/twelvemonkeys/BaseTwelveMonkeysTest.java
import com.twelvemonkeys.image.ResampleOp;
import org.github.jipsg.common.AbstractImageTest;
import org.github.jipsg.common.image.BufferedImageUtils;
import javax.imageio.ImageIO;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.github.jipsg.twelvemonkeys;
/**
* Base class for testing TwelveMonkey library.
*/
public class BaseTwelveMonkeysTest extends AbstractImageTest {
@Override
public void setup() {
super.setModuleName("twelvemonkeys");
super.setup();
}
@Override
public BufferedImage createBufferedImage(File file) throws Exception {
return ImageIO.read(file);
}
@Override
public void writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
System.out.println("Saving " + file.getPath());
ImageIO.write(bufferedImage, formatName, file);
}
@Override
public void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
Dimension boundaryDimension = new Dimension(width, height); | Dimension scaledDimension = BufferedImageUtils.getScaledDimension(imageDimension, boundaryDimension); |
sgoeschl/java-image-processing-survival-guide | code/jipsg/image-manipulation/src/test/java/org/github/jipsg/image/comparison/InvertingImageComparator.java | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/ops/InvertImageOp.java
// public class InvertImageOp implements BufferedImageOp {
//
// public BufferedImage filter(BufferedImage src, BufferedImage dest) {
// RescaleOp op = new RescaleOp(-1.0f, 255f, null);
// return op.filter(src, dest);
// }
//
// public Rectangle2D getBounds2D(BufferedImage src) {
// return null;
// }
//
// public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
// return null;
// }
//
// public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) {
// return null;
// }
//
// public RenderingHints getRenderingHints() {
// return null;
// }
// }
| import org.github.jipsg.common.image.ops.InvertImageOp;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter; | package org.github.jipsg.image.comparison;
/**
* Created by sgoeschl on 18/11/14.
*/
public class InvertingImageComparator {
public BufferedImage compare(BufferedImage bim1, BufferedImage bim2) {
// create an inverted image | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/ops/InvertImageOp.java
// public class InvertImageOp implements BufferedImageOp {
//
// public BufferedImage filter(BufferedImage src, BufferedImage dest) {
// RescaleOp op = new RescaleOp(-1.0f, 255f, null);
// return op.filter(src, dest);
// }
//
// public Rectangle2D getBounds2D(BufferedImage src) {
// return null;
// }
//
// public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
// return null;
// }
//
// public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) {
// return null;
// }
//
// public RenderingHints getRenderingHints() {
// return null;
// }
// }
// Path: code/jipsg/image-manipulation/src/test/java/org/github/jipsg/image/comparison/InvertingImageComparator.java
import org.github.jipsg.common.image.ops.InvertImageOp;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
package org.github.jipsg.image.comparison;
/**
* Created by sgoeschl on 18/11/14.
*/
public class InvertingImageComparator {
public BufferedImage compare(BufferedImage bim1, BufferedImage bim2) {
// create an inverted image | InvertImageOp invertImageOp = new InvertImageOp(); |
sgoeschl/java-image-processing-survival-guide | code/jipsg/image-manipulation/src/test/java/org/github/jipsg/image/manipulation/BaseImageManipulationTest.java | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/AbstractImageTest.java
// public abstract class AbstractImageTest {
//
// private String moduleName;
// private File imageDirectory;
//
// public abstract BufferedImage createBufferedImage(final File file) throws Exception;
//
// public abstract void writeBufferedImage(final BufferedImage bufferedImage, final String formatName, final File file) throws Exception;
//
// public abstract BufferedImage resample(final BufferedImage bufferedImage, int width, int height);
//
// public abstract void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception;
//
// public void setup() {
// File currDirectory = new File("");
// if (currDirectory.getAbsolutePath().endsWith("jipsg")) {
// this.imageDirectory = new File("../images");
// } else {
// this.imageDirectory = new File("../../images");
// }
// }
//
// protected void setModuleName(String moduleName) {
// this.moduleName = moduleName;
// }
//
// /**
// * Get the given file.
// *
// * @param folderName Name of the folder under "images"
// * @param fileName File name
// * @return the file
// */
// protected File getImageFile(String folderName, String fileName) throws IOException {
// File folderFile = new File(getImageDirectory(), folderName);
// File result = new File(folderFile, fileName);
// if (!result.exists() || !result.canRead()) {
// throw new IOException("Can't open/read the following file : " + result.getAbsolutePath());
// }
// return result;
// }
//
// /**
// * Some dumb sanity check that we have a valid buffered image.
// */
// protected void assertValidBufferedImage(BufferedImage bufferedImage) {
// assertNotNull("bufferedImage is null", bufferedImage);
// assertTrue(bufferedImage.getHeight() > 0);
// assertTrue(bufferedImage.getWidth() > 0);
// }
//
// protected File createOutputFileName(String directory, File file, String format) {
// return createOutputFileName(directory, file.getName(), format);
// }
//
// protected File createOutputFileName(String directory, String fileName, String format) {
//
// File outputDir = new File(new File(new File(new File("./target"), "out"), this.moduleName), directory);
//
// if (!outputDir.exists()) {
// outputDir.mkdirs();
// }
//
// return new File(outputDir, fileName + "." + format);
// }
//
// private File getImageDirectory() {
// return imageDirectory;
// }
// }
//
// Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageUtils.java
// public class BufferedImageUtils {
//
// public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
//
// int original_width = imgSize.width;
// int original_height = imgSize.height;
// int bound_width = boundary.width;
// int bound_height = boundary.height;
// int new_width = original_width;
// int new_height = original_height;
//
// // first check if we need to scale width
// if (original_width > bound_width) {
// //scale width to fit
// new_width = bound_width;
// //scale height to maintain aspect ratio
// new_height = (new_width * original_height) / original_width;
// }
//
// // then check if we need to scale even with the new height
// if (new_height > bound_height) {
// //scale height to fit instead
// new_height = bound_height;
// //scale width to maintain aspect ratio
// new_width = (new_height * original_width) / original_height;
// }
//
// return new Dimension(new_width, new_height);
// }
// }
| import org.github.jipsg.common.AbstractImageTest;
import org.github.jipsg.common.image.BufferedImageUtils;
import javax.imageio.ImageIO;
import java.awt.Dimension;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.github.jipsg.image.manipulation;
/**
* Base class for testing Java ImageIO.
*/
public class BaseImageManipulationTest extends AbstractImageTest {
@Override
public void setup() {
super.setModuleName("imageio");
super.setup();
}
@Override
public BufferedImage createBufferedImage(File file) throws IOException {
return ImageIO.read(file);
}
@Override
public void writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
ImageIO.write(bufferedImage, formatName, file);
}
@Override
public void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception {
ImageIO.write(bufferedImage, formatName, file);
}
/**
* Some quick and dirty image scaling - please note that for best performance
* and quality you should use image rescaling libraries.
*/
@Override
public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
Dimension boundaryDimension = new Dimension(width, height); | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/AbstractImageTest.java
// public abstract class AbstractImageTest {
//
// private String moduleName;
// private File imageDirectory;
//
// public abstract BufferedImage createBufferedImage(final File file) throws Exception;
//
// public abstract void writeBufferedImage(final BufferedImage bufferedImage, final String formatName, final File file) throws Exception;
//
// public abstract BufferedImage resample(final BufferedImage bufferedImage, int width, int height);
//
// public abstract void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception;
//
// public void setup() {
// File currDirectory = new File("");
// if (currDirectory.getAbsolutePath().endsWith("jipsg")) {
// this.imageDirectory = new File("../images");
// } else {
// this.imageDirectory = new File("../../images");
// }
// }
//
// protected void setModuleName(String moduleName) {
// this.moduleName = moduleName;
// }
//
// /**
// * Get the given file.
// *
// * @param folderName Name of the folder under "images"
// * @param fileName File name
// * @return the file
// */
// protected File getImageFile(String folderName, String fileName) throws IOException {
// File folderFile = new File(getImageDirectory(), folderName);
// File result = new File(folderFile, fileName);
// if (!result.exists() || !result.canRead()) {
// throw new IOException("Can't open/read the following file : " + result.getAbsolutePath());
// }
// return result;
// }
//
// /**
// * Some dumb sanity check that we have a valid buffered image.
// */
// protected void assertValidBufferedImage(BufferedImage bufferedImage) {
// assertNotNull("bufferedImage is null", bufferedImage);
// assertTrue(bufferedImage.getHeight() > 0);
// assertTrue(bufferedImage.getWidth() > 0);
// }
//
// protected File createOutputFileName(String directory, File file, String format) {
// return createOutputFileName(directory, file.getName(), format);
// }
//
// protected File createOutputFileName(String directory, String fileName, String format) {
//
// File outputDir = new File(new File(new File(new File("./target"), "out"), this.moduleName), directory);
//
// if (!outputDir.exists()) {
// outputDir.mkdirs();
// }
//
// return new File(outputDir, fileName + "." + format);
// }
//
// private File getImageDirectory() {
// return imageDirectory;
// }
// }
//
// Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageUtils.java
// public class BufferedImageUtils {
//
// public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
//
// int original_width = imgSize.width;
// int original_height = imgSize.height;
// int bound_width = boundary.width;
// int bound_height = boundary.height;
// int new_width = original_width;
// int new_height = original_height;
//
// // first check if we need to scale width
// if (original_width > bound_width) {
// //scale width to fit
// new_width = bound_width;
// //scale height to maintain aspect ratio
// new_height = (new_width * original_height) / original_width;
// }
//
// // then check if we need to scale even with the new height
// if (new_height > bound_height) {
// //scale height to fit instead
// new_height = bound_height;
// //scale width to maintain aspect ratio
// new_width = (new_height * original_width) / original_height;
// }
//
// return new Dimension(new_width, new_height);
// }
// }
// Path: code/jipsg/image-manipulation/src/test/java/org/github/jipsg/image/manipulation/BaseImageManipulationTest.java
import org.github.jipsg.common.AbstractImageTest;
import org.github.jipsg.common.image.BufferedImageUtils;
import javax.imageio.ImageIO;
import java.awt.Dimension;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.github.jipsg.image.manipulation;
/**
* Base class for testing Java ImageIO.
*/
public class BaseImageManipulationTest extends AbstractImageTest {
@Override
public void setup() {
super.setModuleName("imageio");
super.setup();
}
@Override
public BufferedImage createBufferedImage(File file) throws IOException {
return ImageIO.read(file);
}
@Override
public void writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
ImageIO.write(bufferedImage, formatName, file);
}
@Override
public void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception {
ImageIO.write(bufferedImage, formatName, file);
}
/**
* Some quick and dirty image scaling - please note that for best performance
* and quality you should use image rescaling libraries.
*/
@Override
public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
Dimension boundaryDimension = new Dimension(width, height); | Dimension scaledDimension = BufferedImageUtils.getScaledDimension(imageDimension, boundaryDimension); |
sgoeschl/java-image-processing-survival-guide | code/jipsg/thumbnailator/src/test/java/org/github/jipsg/thumbnailator/ImageScalingThumbnailatorTest.java | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// public static BufferedImage create(Object source) throws Exception {
//
// BufferedImage result;
//
// if (source instanceof File) {
// File sourceFile = (File) source;
// result = ImageIO.read(sourceFile);
// } else if (source instanceof String) {
// File sourceFile = new File(source.toString());
// result = ImageIO.read(sourceFile);
// } else {
// throw new IllegalArgumentException("Don't know how to handle : " + source.getClass().getName());
// }
//
// return result;
// }
//
// public static boolean writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
// System.out.println("Saving " + file.getPath());
// return ImageIO.write(bufferedImage, formatName, file);
// }
// }
| import junit.framework.TestCase;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.resizers.configurations.Antialiasing;
import org.github.jipsg.common.image.BufferedImageFactory;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.github.jipsg.thumbnailator;
/**
* Image manipulation samples.
*/
public class ImageScalingThumbnailatorTest extends TestCase {
public File createOutputFileName(String directory, String fileName, String format) {
File outputDir = new File(new File(new File(new File("./target"), "out"), "thumbnailator"), directory);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
return new File(outputDir, fileName + "." + format);
}
public File createOutputFileName(String directory, File file, String format) {
return createOutputFileName(directory, file.getName(), format);
}
// ======================================================================
// Image Scaling
// ======================================================================
@Test
public void testScaleImages() throws Exception {
final int[] IMAGE_SCALE_DIMENSIONS = new int[] {575, 199, 80, 60};
final float QUALITY = 0.8f;
File sourceImageDir = new File("../../images/willhaben");
File[] sourceImageFiles = sourceImageDir.listFiles();
long currentTime = System.currentTimeMillis();
for (File sourceImageFile : sourceImageFiles) {
BufferedImage bufferedImage = ImageIO.read(sourceImageFile);
for (int size : IMAGE_SCALE_DIMENSIONS) {
BufferedImage scaledBufferedImage = Thumbnails.of(bufferedImage).
width(size).
height(size).
keepAspectRatio(true).
outputQuality(QUALITY).
antialiasing(Antialiasing.ON).
asBufferedImage();
bufferedImage = scaledBufferedImage;
| // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// public static BufferedImage create(Object source) throws Exception {
//
// BufferedImage result;
//
// if (source instanceof File) {
// File sourceFile = (File) source;
// result = ImageIO.read(sourceFile);
// } else if (source instanceof String) {
// File sourceFile = new File(source.toString());
// result = ImageIO.read(sourceFile);
// } else {
// throw new IllegalArgumentException("Don't know how to handle : " + source.getClass().getName());
// }
//
// return result;
// }
//
// public static boolean writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
// System.out.println("Saving " + file.getPath());
// return ImageIO.write(bufferedImage, formatName, file);
// }
// }
// Path: code/jipsg/thumbnailator/src/test/java/org/github/jipsg/thumbnailator/ImageScalingThumbnailatorTest.java
import junit.framework.TestCase;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.resizers.configurations.Antialiasing;
import org.github.jipsg.common.image.BufferedImageFactory;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.github.jipsg.thumbnailator;
/**
* Image manipulation samples.
*/
public class ImageScalingThumbnailatorTest extends TestCase {
public File createOutputFileName(String directory, String fileName, String format) {
File outputDir = new File(new File(new File(new File("./target"), "out"), "thumbnailator"), directory);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
return new File(outputDir, fileName + "." + format);
}
public File createOutputFileName(String directory, File file, String format) {
return createOutputFileName(directory, file.getName(), format);
}
// ======================================================================
// Image Scaling
// ======================================================================
@Test
public void testScaleImages() throws Exception {
final int[] IMAGE_SCALE_DIMENSIONS = new int[] {575, 199, 80, 60};
final float QUALITY = 0.8f;
File sourceImageDir = new File("../../images/willhaben");
File[] sourceImageFiles = sourceImageDir.listFiles();
long currentTime = System.currentTimeMillis();
for (File sourceImageFile : sourceImageFiles) {
BufferedImage bufferedImage = ImageIO.read(sourceImageFile);
for (int size : IMAGE_SCALE_DIMENSIONS) {
BufferedImage scaledBufferedImage = Thumbnails.of(bufferedImage).
width(size).
height(size).
keepAspectRatio(true).
outputQuality(QUALITY).
antialiasing(Antialiasing.ON).
asBufferedImage();
bufferedImage = scaledBufferedImage;
| BufferedImageFactory.writeBufferedImage(scaledBufferedImage, "jpeg", createOutputFileName("testScaleImages/" + size, sourceImageFile, "jpeg")); |
sgoeschl/java-image-processing-survival-guide | code/jipsg/image-manipulation/src/test/java/org/github/jipsg/image/comparison/InvertedImageComparatorTest.java | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// public static BufferedImage create(Object source) throws Exception {
//
// BufferedImage result;
//
// if (source instanceof File) {
// File sourceFile = (File) source;
// result = ImageIO.read(sourceFile);
// } else if (source instanceof String) {
// File sourceFile = new File(source.toString());
// result = ImageIO.read(sourceFile);
// } else {
// throw new IllegalArgumentException("Don't know how to handle : " + source.getClass().getName());
// }
//
// return result;
// }
//
// public static boolean writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
// System.out.println("Saving " + file.getPath());
// return ImageIO.write(bufferedImage, formatName, file);
// }
// }
//
// Path: code/jipsg/imageio/src/main/java/org/github/jipsg/imageio/BaseImageIoTest.java
// public class BaseImageIoTest extends AbstractImageTest {
//
// @Override
// public void setup() {
// super.setModuleName("imageio");
// super.setup();
// }
//
// @Override
// public BufferedImage createBufferedImage(File file) throws IOException {
// return ImageIO.read(file);
// }
//
// @Override
// public void writeBufferedImage(BufferedImage bufferedImage, String formatName, File targetFile) throws Exception {
// System.out.println("Saving " + targetFile.getPath());
// ImageIO.write(bufferedImage, formatName, targetFile);
// }
//
// @Override
// public void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File targetFile) throws Exception {
//
// System.out.println("Saving " + targetFile.getPath());
//
// if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
// JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix(formatName).next();
// ImageWriteParam writeParam = imageWriter.getDefaultWriteParam();
// ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
// IIOMetadata metadata = imageWriter.getDefaultImageMetadata(typeSpecifier, writeParam);
//
// if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
// Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
// Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
// jfif.setAttribute("Xdensity", Integer.toString(dpi));
// jfif.setAttribute("Ydensity", Integer.toString(dpi));
// jfif.setAttribute("resUnits", "1");
// metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
// }
//
// if (quality >= 0 && quality <= 1f) {
// JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
// jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
// jpegParams.setCompressionQuality(quality);
// }
//
// FileOutputStream os = new FileOutputStream(targetFile);
// final ImageOutputStream stream = ImageIO.createImageOutputStream(os);
//
// try {
// imageWriter.setOutput(stream);
// imageWriter.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
// } finally {
// stream.close();
// }
// } else {
// writeBufferedImage(bufferedImage, formatName, targetFile);
// }
// }
//
// /**
// * Some quick and dirty image scaling - please note that for best performance
// * and quality you should use image rescaling libraries.
// */
// @Override
// public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
// Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
// Dimension boundaryDimension = new Dimension(width, height);
// Dimension scaledDimension = BufferedImageUtils.getScaledDimension(imageDimension, boundaryDimension);
//
// double scaleX = scaledDimension.getWidth() / bufferedImage.getWidth();
// double scaleY = scaledDimension.getHeight() / bufferedImage.getHeight();
//
// AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
// AffineTransformOp biLinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
//
// return biLinearScaleOp.filter(
// bufferedImage,
// new BufferedImage(scaledDimension.width, scaledDimension.height, bufferedImage.getType()));
// }
// }
| import org.github.jipsg.common.image.BufferedImageFactory;
import org.github.jipsg.imageio.BaseImageIoTest;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.File; | package org.github.jipsg.image.comparison;
/**
* Created by sgoeschl on 18/11/14.
*/
public class InvertedImageComparatorTest extends BaseImageIoTest {
@Override
public void setup() {
super.setModuleName("image-processing");
super.setup();
}
@Test
public void testIdenticalImage() throws Exception {
| // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// public static BufferedImage create(Object source) throws Exception {
//
// BufferedImage result;
//
// if (source instanceof File) {
// File sourceFile = (File) source;
// result = ImageIO.read(sourceFile);
// } else if (source instanceof String) {
// File sourceFile = new File(source.toString());
// result = ImageIO.read(sourceFile);
// } else {
// throw new IllegalArgumentException("Don't know how to handle : " + source.getClass().getName());
// }
//
// return result;
// }
//
// public static boolean writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
// System.out.println("Saving " + file.getPath());
// return ImageIO.write(bufferedImage, formatName, file);
// }
// }
//
// Path: code/jipsg/imageio/src/main/java/org/github/jipsg/imageio/BaseImageIoTest.java
// public class BaseImageIoTest extends AbstractImageTest {
//
// @Override
// public void setup() {
// super.setModuleName("imageio");
// super.setup();
// }
//
// @Override
// public BufferedImage createBufferedImage(File file) throws IOException {
// return ImageIO.read(file);
// }
//
// @Override
// public void writeBufferedImage(BufferedImage bufferedImage, String formatName, File targetFile) throws Exception {
// System.out.println("Saving " + targetFile.getPath());
// ImageIO.write(bufferedImage, formatName, targetFile);
// }
//
// @Override
// public void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File targetFile) throws Exception {
//
// System.out.println("Saving " + targetFile.getPath());
//
// if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
// JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix(formatName).next();
// ImageWriteParam writeParam = imageWriter.getDefaultWriteParam();
// ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
// IIOMetadata metadata = imageWriter.getDefaultImageMetadata(typeSpecifier, writeParam);
//
// if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
// Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
// Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
// jfif.setAttribute("Xdensity", Integer.toString(dpi));
// jfif.setAttribute("Ydensity", Integer.toString(dpi));
// jfif.setAttribute("resUnits", "1");
// metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
// }
//
// if (quality >= 0 && quality <= 1f) {
// JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
// jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
// jpegParams.setCompressionQuality(quality);
// }
//
// FileOutputStream os = new FileOutputStream(targetFile);
// final ImageOutputStream stream = ImageIO.createImageOutputStream(os);
//
// try {
// imageWriter.setOutput(stream);
// imageWriter.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
// } finally {
// stream.close();
// }
// } else {
// writeBufferedImage(bufferedImage, formatName, targetFile);
// }
// }
//
// /**
// * Some quick and dirty image scaling - please note that for best performance
// * and quality you should use image rescaling libraries.
// */
// @Override
// public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
// Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
// Dimension boundaryDimension = new Dimension(width, height);
// Dimension scaledDimension = BufferedImageUtils.getScaledDimension(imageDimension, boundaryDimension);
//
// double scaleX = scaledDimension.getWidth() / bufferedImage.getWidth();
// double scaleY = scaledDimension.getHeight() / bufferedImage.getHeight();
//
// AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
// AffineTransformOp biLinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
//
// return biLinearScaleOp.filter(
// bufferedImage,
// new BufferedImage(scaledDimension.width, scaledDimension.height, bufferedImage.getType()));
// }
// }
// Path: code/jipsg/image-manipulation/src/test/java/org/github/jipsg/image/comparison/InvertedImageComparatorTest.java
import org.github.jipsg.common.image.BufferedImageFactory;
import org.github.jipsg.imageio.BaseImageIoTest;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.File;
package org.github.jipsg.image.comparison;
/**
* Created by sgoeschl on 18/11/14.
*/
public class InvertedImageComparatorTest extends BaseImageIoTest {
@Override
public void setup() {
super.setModuleName("image-processing");
super.setup();
}
@Test
public void testIdenticalImage() throws Exception {
| final BufferedImage bufferedImage1 = BufferedImageFactory.create("../../images/samples/open-office-01.pdf.300.0.png"); |
sgoeschl/java-image-processing-survival-guide | code/jipsg/image-manipulation/src/test/java/org/github/jipsg/image/comparison/IdenticalImageComparatorTest.java | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// public static BufferedImage create(Object source) throws Exception {
//
// BufferedImage result;
//
// if (source instanceof File) {
// File sourceFile = (File) source;
// result = ImageIO.read(sourceFile);
// } else if (source instanceof String) {
// File sourceFile = new File(source.toString());
// result = ImageIO.read(sourceFile);
// } else {
// throw new IllegalArgumentException("Don't know how to handle : " + source.getClass().getName());
// }
//
// return result;
// }
//
// public static boolean writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
// System.out.println("Saving " + file.getPath());
// return ImageIO.write(bufferedImage, formatName, file);
// }
// }
//
// Path: code/jipsg/imageio/src/main/java/org/github/jipsg/imageio/BaseImageIoTest.java
// public class BaseImageIoTest extends AbstractImageTest {
//
// @Override
// public void setup() {
// super.setModuleName("imageio");
// super.setup();
// }
//
// @Override
// public BufferedImage createBufferedImage(File file) throws IOException {
// return ImageIO.read(file);
// }
//
// @Override
// public void writeBufferedImage(BufferedImage bufferedImage, String formatName, File targetFile) throws Exception {
// System.out.println("Saving " + targetFile.getPath());
// ImageIO.write(bufferedImage, formatName, targetFile);
// }
//
// @Override
// public void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File targetFile) throws Exception {
//
// System.out.println("Saving " + targetFile.getPath());
//
// if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
// JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix(formatName).next();
// ImageWriteParam writeParam = imageWriter.getDefaultWriteParam();
// ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
// IIOMetadata metadata = imageWriter.getDefaultImageMetadata(typeSpecifier, writeParam);
//
// if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
// Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
// Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
// jfif.setAttribute("Xdensity", Integer.toString(dpi));
// jfif.setAttribute("Ydensity", Integer.toString(dpi));
// jfif.setAttribute("resUnits", "1");
// metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
// }
//
// if (quality >= 0 && quality <= 1f) {
// JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
// jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
// jpegParams.setCompressionQuality(quality);
// }
//
// FileOutputStream os = new FileOutputStream(targetFile);
// final ImageOutputStream stream = ImageIO.createImageOutputStream(os);
//
// try {
// imageWriter.setOutput(stream);
// imageWriter.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
// } finally {
// stream.close();
// }
// } else {
// writeBufferedImage(bufferedImage, formatName, targetFile);
// }
// }
//
// /**
// * Some quick and dirty image scaling - please note that for best performance
// * and quality you should use image rescaling libraries.
// */
// @Override
// public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
// Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
// Dimension boundaryDimension = new Dimension(width, height);
// Dimension scaledDimension = BufferedImageUtils.getScaledDimension(imageDimension, boundaryDimension);
//
// double scaleX = scaledDimension.getWidth() / bufferedImage.getWidth();
// double scaleY = scaledDimension.getHeight() / bufferedImage.getHeight();
//
// AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
// AffineTransformOp biLinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
//
// return biLinearScaleOp.filter(
// bufferedImage,
// new BufferedImage(scaledDimension.width, scaledDimension.height, bufferedImage.getType()));
// }
// }
| import org.github.jipsg.common.image.BufferedImageFactory;
import org.github.jipsg.imageio.BaseImageIoTest;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.File;
import static org.junit.Assert.assertNull; | package org.github.jipsg.image.comparison;
/**
* Created by sgoeschl on 18/11/14.
*/
public class IdenticalImageComparatorTest extends BaseImageIoTest {
@Override
public void setup() {
super.setModuleName("image-processing");
super.setup();
}
@Test
public void testIdenticalImage() throws Exception {
| // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// public static BufferedImage create(Object source) throws Exception {
//
// BufferedImage result;
//
// if (source instanceof File) {
// File sourceFile = (File) source;
// result = ImageIO.read(sourceFile);
// } else if (source instanceof String) {
// File sourceFile = new File(source.toString());
// result = ImageIO.read(sourceFile);
// } else {
// throw new IllegalArgumentException("Don't know how to handle : " + source.getClass().getName());
// }
//
// return result;
// }
//
// public static boolean writeBufferedImage(BufferedImage bufferedImage, String formatName, File file) throws Exception {
// System.out.println("Saving " + file.getPath());
// return ImageIO.write(bufferedImage, formatName, file);
// }
// }
//
// Path: code/jipsg/imageio/src/main/java/org/github/jipsg/imageio/BaseImageIoTest.java
// public class BaseImageIoTest extends AbstractImageTest {
//
// @Override
// public void setup() {
// super.setModuleName("imageio");
// super.setup();
// }
//
// @Override
// public BufferedImage createBufferedImage(File file) throws IOException {
// return ImageIO.read(file);
// }
//
// @Override
// public void writeBufferedImage(BufferedImage bufferedImage, String formatName, File targetFile) throws Exception {
// System.out.println("Saving " + targetFile.getPath());
// ImageIO.write(bufferedImage, formatName, targetFile);
// }
//
// @Override
// public void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File targetFile) throws Exception {
//
// System.out.println("Saving " + targetFile.getPath());
//
// if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
// JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix(formatName).next();
// ImageWriteParam writeParam = imageWriter.getDefaultWriteParam();
// ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
// IIOMetadata metadata = imageWriter.getDefaultImageMetadata(typeSpecifier, writeParam);
//
// if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
// Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
// Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
// jfif.setAttribute("Xdensity", Integer.toString(dpi));
// jfif.setAttribute("Ydensity", Integer.toString(dpi));
// jfif.setAttribute("resUnits", "1");
// metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
// }
//
// if (quality >= 0 && quality <= 1f) {
// JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
// jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
// jpegParams.setCompressionQuality(quality);
// }
//
// FileOutputStream os = new FileOutputStream(targetFile);
// final ImageOutputStream stream = ImageIO.createImageOutputStream(os);
//
// try {
// imageWriter.setOutput(stream);
// imageWriter.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
// } finally {
// stream.close();
// }
// } else {
// writeBufferedImage(bufferedImage, formatName, targetFile);
// }
// }
//
// /**
// * Some quick and dirty image scaling - please note that for best performance
// * and quality you should use image rescaling libraries.
// */
// @Override
// public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
// Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
// Dimension boundaryDimension = new Dimension(width, height);
// Dimension scaledDimension = BufferedImageUtils.getScaledDimension(imageDimension, boundaryDimension);
//
// double scaleX = scaledDimension.getWidth() / bufferedImage.getWidth();
// double scaleY = scaledDimension.getHeight() / bufferedImage.getHeight();
//
// AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
// AffineTransformOp biLinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
//
// return biLinearScaleOp.filter(
// bufferedImage,
// new BufferedImage(scaledDimension.width, scaledDimension.height, bufferedImage.getType()));
// }
// }
// Path: code/jipsg/image-manipulation/src/test/java/org/github/jipsg/image/comparison/IdenticalImageComparatorTest.java
import org.github.jipsg.common.image.BufferedImageFactory;
import org.github.jipsg.imageio.BaseImageIoTest;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.File;
import static org.junit.Assert.assertNull;
package org.github.jipsg.image.comparison;
/**
* Created by sgoeschl on 18/11/14.
*/
public class IdenticalImageComparatorTest extends BaseImageIoTest {
@Override
public void setup() {
super.setModuleName("image-processing");
super.setup();
}
@Test
public void testIdenticalImage() throws Exception {
| final BufferedImage bufferedImage1 = BufferedImageFactory.create("../../images/samples/open-office-01.pdf.300.0.png"); |
sgoeschl/java-image-processing-survival-guide | code/jipsg/imageio/src/main/java/org/github/jipsg/imageio/BaseImageIoTest.java | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/AbstractImageTest.java
// public abstract class AbstractImageTest {
//
// private String moduleName;
// private File imageDirectory;
//
// public abstract BufferedImage createBufferedImage(final File file) throws Exception;
//
// public abstract void writeBufferedImage(final BufferedImage bufferedImage, final String formatName, final File file) throws Exception;
//
// public abstract BufferedImage resample(final BufferedImage bufferedImage, int width, int height);
//
// public abstract void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception;
//
// public void setup() {
// File currDirectory = new File("");
// if (currDirectory.getAbsolutePath().endsWith("jipsg")) {
// this.imageDirectory = new File("../images");
// } else {
// this.imageDirectory = new File("../../images");
// }
// }
//
// protected void setModuleName(String moduleName) {
// this.moduleName = moduleName;
// }
//
// /**
// * Get the given file.
// *
// * @param folderName Name of the folder under "images"
// * @param fileName File name
// * @return the file
// */
// protected File getImageFile(String folderName, String fileName) throws IOException {
// File folderFile = new File(getImageDirectory(), folderName);
// File result = new File(folderFile, fileName);
// if (!result.exists() || !result.canRead()) {
// throw new IOException("Can't open/read the following file : " + result.getAbsolutePath());
// }
// return result;
// }
//
// /**
// * Some dumb sanity check that we have a valid buffered image.
// */
// protected void assertValidBufferedImage(BufferedImage bufferedImage) {
// assertNotNull("bufferedImage is null", bufferedImage);
// assertTrue(bufferedImage.getHeight() > 0);
// assertTrue(bufferedImage.getWidth() > 0);
// }
//
// protected File createOutputFileName(String directory, File file, String format) {
// return createOutputFileName(directory, file.getName(), format);
// }
//
// protected File createOutputFileName(String directory, String fileName, String format) {
//
// File outputDir = new File(new File(new File(new File("./target"), "out"), this.moduleName), directory);
//
// if (!outputDir.exists()) {
// outputDir.mkdirs();
// }
//
// return new File(outputDir, fileName + "." + format);
// }
//
// private File getImageDirectory() {
// return imageDirectory;
// }
// }
//
// Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageUtils.java
// public class BufferedImageUtils {
//
// public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
//
// int original_width = imgSize.width;
// int original_height = imgSize.height;
// int bound_width = boundary.width;
// int bound_height = boundary.height;
// int new_width = original_width;
// int new_height = original_height;
//
// // first check if we need to scale width
// if (original_width > bound_width) {
// //scale width to fit
// new_width = bound_width;
// //scale height to maintain aspect ratio
// new_height = (new_width * original_height) / original_width;
// }
//
// // then check if we need to scale even with the new height
// if (new_height > bound_height) {
// //scale height to fit instead
// new_height = bound_height;
// //scale width to maintain aspect ratio
// new_width = (new_height * original_width) / original_height;
// }
//
// return new Dimension(new_width, new_height);
// }
// }
| import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.sun.imageio.plugins.jpeg.JPEGImageWriter;
import org.github.jipsg.common.AbstractImageTest;
import org.github.jipsg.common.image.BufferedImageUtils;
import org.w3c.dom.Element;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import java.awt.Dimension;
import java.awt.geom.AffineTransform; | }
if (quality >= 0 && quality <= 1f) {
JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality);
}
FileOutputStream os = new FileOutputStream(targetFile);
final ImageOutputStream stream = ImageIO.createImageOutputStream(os);
try {
imageWriter.setOutput(stream);
imageWriter.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
} finally {
stream.close();
}
} else {
writeBufferedImage(bufferedImage, formatName, targetFile);
}
}
/**
* Some quick and dirty image scaling - please note that for best performance
* and quality you should use image rescaling libraries.
*/
@Override
public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
Dimension boundaryDimension = new Dimension(width, height); | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/AbstractImageTest.java
// public abstract class AbstractImageTest {
//
// private String moduleName;
// private File imageDirectory;
//
// public abstract BufferedImage createBufferedImage(final File file) throws Exception;
//
// public abstract void writeBufferedImage(final BufferedImage bufferedImage, final String formatName, final File file) throws Exception;
//
// public abstract BufferedImage resample(final BufferedImage bufferedImage, int width, int height);
//
// public abstract void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception;
//
// public void setup() {
// File currDirectory = new File("");
// if (currDirectory.getAbsolutePath().endsWith("jipsg")) {
// this.imageDirectory = new File("../images");
// } else {
// this.imageDirectory = new File("../../images");
// }
// }
//
// protected void setModuleName(String moduleName) {
// this.moduleName = moduleName;
// }
//
// /**
// * Get the given file.
// *
// * @param folderName Name of the folder under "images"
// * @param fileName File name
// * @return the file
// */
// protected File getImageFile(String folderName, String fileName) throws IOException {
// File folderFile = new File(getImageDirectory(), folderName);
// File result = new File(folderFile, fileName);
// if (!result.exists() || !result.canRead()) {
// throw new IOException("Can't open/read the following file : " + result.getAbsolutePath());
// }
// return result;
// }
//
// /**
// * Some dumb sanity check that we have a valid buffered image.
// */
// protected void assertValidBufferedImage(BufferedImage bufferedImage) {
// assertNotNull("bufferedImage is null", bufferedImage);
// assertTrue(bufferedImage.getHeight() > 0);
// assertTrue(bufferedImage.getWidth() > 0);
// }
//
// protected File createOutputFileName(String directory, File file, String format) {
// return createOutputFileName(directory, file.getName(), format);
// }
//
// protected File createOutputFileName(String directory, String fileName, String format) {
//
// File outputDir = new File(new File(new File(new File("./target"), "out"), this.moduleName), directory);
//
// if (!outputDir.exists()) {
// outputDir.mkdirs();
// }
//
// return new File(outputDir, fileName + "." + format);
// }
//
// private File getImageDirectory() {
// return imageDirectory;
// }
// }
//
// Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageUtils.java
// public class BufferedImageUtils {
//
// public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
//
// int original_width = imgSize.width;
// int original_height = imgSize.height;
// int bound_width = boundary.width;
// int bound_height = boundary.height;
// int new_width = original_width;
// int new_height = original_height;
//
// // first check if we need to scale width
// if (original_width > bound_width) {
// //scale width to fit
// new_width = bound_width;
// //scale height to maintain aspect ratio
// new_height = (new_width * original_height) / original_width;
// }
//
// // then check if we need to scale even with the new height
// if (new_height > bound_height) {
// //scale height to fit instead
// new_height = bound_height;
// //scale width to maintain aspect ratio
// new_width = (new_height * original_width) / original_height;
// }
//
// return new Dimension(new_width, new_height);
// }
// }
// Path: code/jipsg/imageio/src/main/java/org/github/jipsg/imageio/BaseImageIoTest.java
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.sun.imageio.plugins.jpeg.JPEGImageWriter;
import org.github.jipsg.common.AbstractImageTest;
import org.github.jipsg.common.image.BufferedImageUtils;
import org.w3c.dom.Element;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import java.awt.Dimension;
import java.awt.geom.AffineTransform;
}
if (quality >= 0 && quality <= 1f) {
JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality);
}
FileOutputStream os = new FileOutputStream(targetFile);
final ImageOutputStream stream = ImageIO.createImageOutputStream(os);
try {
imageWriter.setOutput(stream);
imageWriter.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
} finally {
stream.close();
}
} else {
writeBufferedImage(bufferedImage, formatName, targetFile);
}
}
/**
* Some quick and dirty image scaling - please note that for best performance
* and quality you should use image rescaling libraries.
*/
@Override
public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
Dimension boundaryDimension = new Dimension(width, height); | Dimension scaledDimension = BufferedImageUtils.getScaledDimension(imageDimension, boundaryDimension); |
sgoeschl/java-image-processing-survival-guide | code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageOperations.java | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/ops/AlphaChannelImageOp.java
// public class AlphaChannelImageOp implements BufferedImageOp {
//
// /**
// * Fill the alpha-channel with white pixels.
// */
// public BufferedImage filter(BufferedImage src, BufferedImage dest) {
// BufferedImage result = new BufferedImage(src.getWidth(null), src.getHeight(null), BufferedImage.TYPE_INT_RGB);
// Graphics2D g = result.createGraphics();
// g.drawImage(src, 0, 0, result.getWidth(), result.getHeight(), Color.WHITE, null);
// return result;
// }
//
// public Rectangle2D getBounds2D(BufferedImage src) {
// return null;
// }
//
// public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
// return null;
// }
//
// public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) {
// return null;
// }
//
// public RenderingHints getRenderingHints() {
// return null;
// }
// }
| import org.github.jipsg.common.image.ops.AlphaChannelImageOp;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.util.Collection; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.github.jipsg.common.image;
/**
* Contains ready-to use image operations without additional dependencies.
*/
public class BufferedImageOperations {
public static BufferedImage fillTransparentPixel(BufferedImage src) {
// Since JDK 5 the JPG conversion messes up images with alpha-channels
// therefore fill the alpha-channel with white pixels
if (src.getColorModel().hasAlpha()) { | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/ops/AlphaChannelImageOp.java
// public class AlphaChannelImageOp implements BufferedImageOp {
//
// /**
// * Fill the alpha-channel with white pixels.
// */
// public BufferedImage filter(BufferedImage src, BufferedImage dest) {
// BufferedImage result = new BufferedImage(src.getWidth(null), src.getHeight(null), BufferedImage.TYPE_INT_RGB);
// Graphics2D g = result.createGraphics();
// g.drawImage(src, 0, 0, result.getWidth(), result.getHeight(), Color.WHITE, null);
// return result;
// }
//
// public Rectangle2D getBounds2D(BufferedImage src) {
// return null;
// }
//
// public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
// return null;
// }
//
// public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) {
// return null;
// }
//
// public RenderingHints getRenderingHints() {
// return null;
// }
// }
// Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageOperations.java
import org.github.jipsg.common.image.ops.AlphaChannelImageOp;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.util.Collection;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.github.jipsg.common.image;
/**
* Contains ready-to use image operations without additional dependencies.
*/
public class BufferedImageOperations {
public static BufferedImage fillTransparentPixel(BufferedImage src) {
// Since JDK 5 the JPG conversion messes up images with alpha-channels
// therefore fill the alpha-channel with white pixels
if (src.getColorModel().hasAlpha()) { | return apply(src, new AlphaChannelImageOp()); |
sgoeschl/java-image-processing-survival-guide | code/jipsg/jai/src/test/java/org/github/jipsg/jai/AbstractJaiTest.java | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/AbstractImageTest.java
// public abstract class AbstractImageTest {
//
// private String moduleName;
// private File imageDirectory;
//
// public abstract BufferedImage createBufferedImage(final File file) throws Exception;
//
// public abstract void writeBufferedImage(final BufferedImage bufferedImage, final String formatName, final File file) throws Exception;
//
// public abstract BufferedImage resample(final BufferedImage bufferedImage, int width, int height);
//
// public abstract void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception;
//
// public void setup() {
// File currDirectory = new File("");
// if (currDirectory.getAbsolutePath().endsWith("jipsg")) {
// this.imageDirectory = new File("../images");
// } else {
// this.imageDirectory = new File("../../images");
// }
// }
//
// protected void setModuleName(String moduleName) {
// this.moduleName = moduleName;
// }
//
// /**
// * Get the given file.
// *
// * @param folderName Name of the folder under "images"
// * @param fileName File name
// * @return the file
// */
// protected File getImageFile(String folderName, String fileName) throws IOException {
// File folderFile = new File(getImageDirectory(), folderName);
// File result = new File(folderFile, fileName);
// if (!result.exists() || !result.canRead()) {
// throw new IOException("Can't open/read the following file : " + result.getAbsolutePath());
// }
// return result;
// }
//
// /**
// * Some dumb sanity check that we have a valid buffered image.
// */
// protected void assertValidBufferedImage(BufferedImage bufferedImage) {
// assertNotNull("bufferedImage is null", bufferedImage);
// assertTrue(bufferedImage.getHeight() > 0);
// assertTrue(bufferedImage.getWidth() > 0);
// }
//
// protected File createOutputFileName(String directory, File file, String format) {
// return createOutputFileName(directory, file.getName(), format);
// }
//
// protected File createOutputFileName(String directory, String fileName, String format) {
//
// File outputDir = new File(new File(new File(new File("./target"), "out"), this.moduleName), directory);
//
// if (!outputDir.exists()) {
// outputDir.mkdirs();
// }
//
// return new File(outputDir, fileName + "." + format);
// }
//
// private File getImageDirectory() {
// return imageDirectory;
// }
// }
//
// Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageUtils.java
// public class BufferedImageUtils {
//
// public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
//
// int original_width = imgSize.width;
// int original_height = imgSize.height;
// int bound_width = boundary.width;
// int bound_height = boundary.height;
// int new_width = original_width;
// int new_height = original_height;
//
// // first check if we need to scale width
// if (original_width > bound_width) {
// //scale width to fit
// new_width = bound_width;
// //scale height to maintain aspect ratio
// new_height = (new_width * original_height) / original_width;
// }
//
// // then check if we need to scale even with the new height
// if (new_height > bound_height) {
// //scale height to fit instead
// new_height = bound_height;
// //scale width to maintain aspect ratio
// new_width = (new_height * original_width) / original_height;
// }
//
// return new Dimension(new_width, new_height);
// }
// }
| import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import com.sun.imageio.plugins.jpeg.JPEGImageWriter;
import org.github.jipsg.common.AbstractImageTest;
import org.github.jipsg.common.image.BufferedImageUtils;
import org.w3c.dom.Element;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import java.awt.Dimension;
import java.awt.geom.AffineTransform; |
JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality);
}
FileOutputStream os = new FileOutputStream(targetFile);
final ImageOutputStream stream = ImageIO.createImageOutputStream(os);
try {
imageWriter.setOutput(stream);
imageWriter.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
} finally {
stream.close();
}
} else {
writeBufferedImage(bufferedImage, formatName, targetFile);
}
}
/**
* Some quick and dirty image scaling - please note that for best performance
* and quality you should use image rescaling libraries.
*/
@Override
public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
Dimension boundaryDimension = new Dimension(width, height); | // Path: code/jipsg/common/src/main/java/org/github/jipsg/common/AbstractImageTest.java
// public abstract class AbstractImageTest {
//
// private String moduleName;
// private File imageDirectory;
//
// public abstract BufferedImage createBufferedImage(final File file) throws Exception;
//
// public abstract void writeBufferedImage(final BufferedImage bufferedImage, final String formatName, final File file) throws Exception;
//
// public abstract BufferedImage resample(final BufferedImage bufferedImage, int width, int height);
//
// public abstract void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File file) throws Exception;
//
// public void setup() {
// File currDirectory = new File("");
// if (currDirectory.getAbsolutePath().endsWith("jipsg")) {
// this.imageDirectory = new File("../images");
// } else {
// this.imageDirectory = new File("../../images");
// }
// }
//
// protected void setModuleName(String moduleName) {
// this.moduleName = moduleName;
// }
//
// /**
// * Get the given file.
// *
// * @param folderName Name of the folder under "images"
// * @param fileName File name
// * @return the file
// */
// protected File getImageFile(String folderName, String fileName) throws IOException {
// File folderFile = new File(getImageDirectory(), folderName);
// File result = new File(folderFile, fileName);
// if (!result.exists() || !result.canRead()) {
// throw new IOException("Can't open/read the following file : " + result.getAbsolutePath());
// }
// return result;
// }
//
// /**
// * Some dumb sanity check that we have a valid buffered image.
// */
// protected void assertValidBufferedImage(BufferedImage bufferedImage) {
// assertNotNull("bufferedImage is null", bufferedImage);
// assertTrue(bufferedImage.getHeight() > 0);
// assertTrue(bufferedImage.getWidth() > 0);
// }
//
// protected File createOutputFileName(String directory, File file, String format) {
// return createOutputFileName(directory, file.getName(), format);
// }
//
// protected File createOutputFileName(String directory, String fileName, String format) {
//
// File outputDir = new File(new File(new File(new File("./target"), "out"), this.moduleName), directory);
//
// if (!outputDir.exists()) {
// outputDir.mkdirs();
// }
//
// return new File(outputDir, fileName + "." + format);
// }
//
// private File getImageDirectory() {
// return imageDirectory;
// }
// }
//
// Path: code/jipsg/common/src/main/java/org/github/jipsg/common/image/BufferedImageUtils.java
// public class BufferedImageUtils {
//
// public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
//
// int original_width = imgSize.width;
// int original_height = imgSize.height;
// int bound_width = boundary.width;
// int bound_height = boundary.height;
// int new_width = original_width;
// int new_height = original_height;
//
// // first check if we need to scale width
// if (original_width > bound_width) {
// //scale width to fit
// new_width = bound_width;
// //scale height to maintain aspect ratio
// new_height = (new_width * original_height) / original_width;
// }
//
// // then check if we need to scale even with the new height
// if (new_height > bound_height) {
// //scale height to fit instead
// new_height = bound_height;
// //scale width to maintain aspect ratio
// new_width = (new_height * original_width) / original_height;
// }
//
// return new Dimension(new_width, new_height);
// }
// }
// Path: code/jipsg/jai/src/test/java/org/github/jipsg/jai/AbstractJaiTest.java
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import com.sun.imageio.plugins.jpeg.JPEGImageWriter;
import org.github.jipsg.common.AbstractImageTest;
import org.github.jipsg.common.image.BufferedImageUtils;
import org.w3c.dom.Element;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import java.awt.Dimension;
import java.awt.geom.AffineTransform;
JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality);
}
FileOutputStream os = new FileOutputStream(targetFile);
final ImageOutputStream stream = ImageIO.createImageOutputStream(os);
try {
imageWriter.setOutput(stream);
imageWriter.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
} finally {
stream.close();
}
} else {
writeBufferedImage(bufferedImage, formatName, targetFile);
}
}
/**
* Some quick and dirty image scaling - please note that for best performance
* and quality you should use image rescaling libraries.
*/
@Override
public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {
Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
Dimension boundaryDimension = new Dimension(width, height); | Dimension scaledDimension = BufferedImageUtils.getScaledDimension(imageDimension, boundaryDimension); |
whizzosoftware/hobson-hub-core | src/main/java/com/whizzosoftware/hobson/bootstrap/api/action/store/MapDBActionStore.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
| import com.whizzosoftware.hobson.api.action.store.ActionStore;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersistenceContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.persist.IdProvider;
import com.whizzosoftware.hobson.api.property.PropertyContainer;
import com.whizzosoftware.hobson.api.property.PropertyContainerSet;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID; | /*
*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.action.store;
/**
* An implementation of ActionStore that uses MapDB for persistent storage.
*
* @author Dan Noguerol
*/
public class MapDBActionStore implements ActionStore {
final private DB db;
private IdProvider idProvider = new ContextPathIdProvider();
private CollectionPersister persister = new CollectionPersister(idProvider);
private CollectionPersistenceContext mctx;
public MapDBActionStore(File file) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
db = DBMaker.newFileDB(file)
.closeOnJvmShutdown()
.make(); | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
// Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/action/store/MapDBActionStore.java
import com.whizzosoftware.hobson.api.action.store.ActionStore;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersistenceContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.persist.IdProvider;
import com.whizzosoftware.hobson.api.property.PropertyContainer;
import com.whizzosoftware.hobson.api.property.PropertyContainerSet;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
/*
*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.action.store;
/**
* An implementation of ActionStore that uses MapDB for persistent storage.
*
* @author Dan Noguerol
*/
public class MapDBActionStore implements ActionStore {
final private DB db;
private IdProvider idProvider = new ContextPathIdProvider();
private CollectionPersister persister = new CollectionPersister(idProvider);
private CollectionPersistenceContext mctx;
public MapDBActionStore(File file) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
db = DBMaker.newFileDB(file)
.closeOnJvmShutdown()
.make(); | mctx = new MapDBCollectionPersistenceContext(db); |
whizzosoftware/hobson-hub-core | src/main/java/com/whizzosoftware/hobson/bootstrap/api/event/EventHandlerAdapter.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/util/EventUtil.java
// public class EventUtil {
// public static final String PROP_EVENT_ID = "eventId";
//
// static public Event createEventFromHobsonEvent(HobsonEvent event) {
// Map map = new HashMap();
// map.put(PROP_EVENT_ID, event.getEventId());
//
// // copy over all event-specific properties
// Map propMap = event.getProperties();
// if (propMap != null) {
// for (Object key : propMap.keySet()) {
// map.put(key, propMap.get(key));
// }
// }
//
// return new Event(EventTopics.GLOBAL, map);
// }
//
// static public Map<String,Object> createMapFromEvent(Event event) {
// Map<String,Object> map = new HashMap<>();
// for (String key : event.getPropertyNames()) {
// map.put(key, event.getProperty(key));
// }
// return map;
// }
// }
| import com.whizzosoftware.hobson.api.event.EventCallbackInvoker;
import com.whizzosoftware.hobson.api.event.EventHandler;
import com.whizzosoftware.hobson.api.event.HobsonEvent;
import com.whizzosoftware.hobson.bootstrap.api.util.EventUtil;
import org.osgi.service.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | /*
*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.event;
/**
* Adapts the OSGi EventAdmin event callback (handleEvent) into a reflection-based invocation of a @EventHandler
* annotated method in the listener.
*
* @author Dan Noguerol
*/
public class EventHandlerAdapter implements org.osgi.service.event.EventHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
private EventFactory eventFactory;
private Object listener;
private EventCallbackInvoker invoker;
private List<MethodRef> methodCache = new ArrayList<>();
public EventHandlerAdapter(EventFactory eventFactory, Object listener, EventCallbackInvoker invoke) {
this.eventFactory = eventFactory;
this.listener = listener;
this.invoker = invoke;
// build reflection cache
for (Method m : listener.getClass().getMethods()) {
if (m.isAnnotationPresent(EventHandler.class)) {
Class[] params = m.getParameterTypes();
if (params.length == 1) {
methodCache.add(new MethodRef(m, params[0]));
}
}
}
}
@Override
public void handleEvent(Event event) {
logger.trace("Received event: {}", event);
| // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/util/EventUtil.java
// public class EventUtil {
// public static final String PROP_EVENT_ID = "eventId";
//
// static public Event createEventFromHobsonEvent(HobsonEvent event) {
// Map map = new HashMap();
// map.put(PROP_EVENT_ID, event.getEventId());
//
// // copy over all event-specific properties
// Map propMap = event.getProperties();
// if (propMap != null) {
// for (Object key : propMap.keySet()) {
// map.put(key, propMap.get(key));
// }
// }
//
// return new Event(EventTopics.GLOBAL, map);
// }
//
// static public Map<String,Object> createMapFromEvent(Event event) {
// Map<String,Object> map = new HashMap<>();
// for (String key : event.getPropertyNames()) {
// map.put(key, event.getProperty(key));
// }
// return map;
// }
// }
// Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/event/EventHandlerAdapter.java
import com.whizzosoftware.hobson.api.event.EventCallbackInvoker;
import com.whizzosoftware.hobson.api.event.EventHandler;
import com.whizzosoftware.hobson.api.event.HobsonEvent;
import com.whizzosoftware.hobson.bootstrap.api.util.EventUtil;
import org.osgi.service.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/*
*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.event;
/**
* Adapts the OSGi EventAdmin event callback (handleEvent) into a reflection-based invocation of a @EventHandler
* annotated method in the listener.
*
* @author Dan Noguerol
*/
public class EventHandlerAdapter implements org.osgi.service.event.EventHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
private EventFactory eventFactory;
private Object listener;
private EventCallbackInvoker invoker;
private List<MethodRef> methodCache = new ArrayList<>();
public EventHandlerAdapter(EventFactory eventFactory, Object listener, EventCallbackInvoker invoke) {
this.eventFactory = eventFactory;
this.listener = listener;
this.invoker = invoke;
// build reflection cache
for (Method m : listener.getClass().getMethods()) {
if (m.isAnnotationPresent(EventHandler.class)) {
Class[] params = m.getParameterTypes();
if (params.length == 1) {
methodCache.add(new MethodRef(m, params[0]));
}
}
}
}
@Override
public void handleEvent(Event event) {
logger.trace("Received event: {}", event);
| Map<String, Object> props = EventUtil.createMapFromEvent(event); |
whizzosoftware/hobson-hub-core | src/main/java/com/whizzosoftware/hobson/bootstrap/api/presence/store/MapDBPresenceStore.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
| import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.presence.PresenceEntity;
import com.whizzosoftware.hobson.api.presence.PresenceEntityContext;
import com.whizzosoftware.hobson.api.presence.PresenceLocation;
import com.whizzosoftware.hobson.api.presence.PresenceLocationContext;
import com.whizzosoftware.hobson.api.presence.store.PresenceStore;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | /*
*******************************************************************************
* Copyright (c) 2015 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.presence.store;
public class MapDBPresenceStore implements PresenceStore {
private static final Logger logger = LoggerFactory.getLogger(MapDBPresenceStore.class);
final private DB db;
private ContextPathIdProvider idProvider = new ContextPathIdProvider();
private CollectionPersister persister = new CollectionPersister(new ContextPathIdProvider());
public MapDBPresenceStore(File file) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
db = DBMaker.newFileDB(file)
.closeOnJvmShutdown()
.make();
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
@Override
public Collection<PresenceEntity> getAllPresenceEntities(HubContext ctx) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
List<PresenceEntity> results = new ArrayList<>(); | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
// Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/presence/store/MapDBPresenceStore.java
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.presence.PresenceEntity;
import com.whizzosoftware.hobson.api.presence.PresenceEntityContext;
import com.whizzosoftware.hobson.api.presence.PresenceLocation;
import com.whizzosoftware.hobson.api.presence.PresenceLocationContext;
import com.whizzosoftware.hobson.api.presence.store.PresenceStore;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/*
*******************************************************************************
* Copyright (c) 2015 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.presence.store;
public class MapDBPresenceStore implements PresenceStore {
private static final Logger logger = LoggerFactory.getLogger(MapDBPresenceStore.class);
final private DB db;
private ContextPathIdProvider idProvider = new ContextPathIdProvider();
private CollectionPersister persister = new CollectionPersister(new ContextPathIdProvider());
public MapDBPresenceStore(File file) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
db = DBMaker.newFileDB(file)
.closeOnJvmShutdown()
.make();
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
@Override
public Collection<PresenceEntity> getAllPresenceEntities(HubContext ctx) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
List<PresenceEntity> results = new ArrayList<>(); | MapDBCollectionPersistenceContext pctx = new MapDBCollectionPersistenceContext(db); |
whizzosoftware/hobson-hub-core | src/test/java/com/whizzosoftware/hobson/bootstrap/api/util/HttpUtilTest.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/HttpUtil.java
// public class HttpUtil {
//
// /**
// * Create a ContentRange object for start and end values.
// *
// * @param start the start of the range
// * @param end the end of the range
// *
// * @return a ContentRange instance
// */
// static public ContentRange createRange(long start, long end) {
// return new ContentRange(start, end);
// }
//
// /**
// * Create a ContentRange object for an RFC-7233 Range string.
// *
// * @param range the Range string
// * @param contentLength the total length of the content
// *
// * @return a ContentRange instance (or null if the range can't be parsed)
// * @throws ParseException on failure
// */
// static public ContentRange createRange(String range, long contentLength) throws ParseException {
// if (range != null) {
// if (range.startsWith("bytes=")) {
// range = range.substring(6, range.length());
// int ix = range.indexOf("-");
// if (ix > -1 && range.length() > 1) {
// try {
// if (ix == 0) {
// return new ContentRange(contentLength - Long.parseLong(range.substring(ix + 1, range.length())), contentLength - 1);
// } else if (ix == range.length() - 1) {
// return new ContentRange(Long.parseLong(range.substring(0, ix)), contentLength - 1);
// } else {
// return new ContentRange(Long.parseLong(range.substring(0, ix)), Long.parseLong(range.substring(ix + 1, range.length())));
// }
// } catch (NumberFormatException ignored) {}
// }
// }
// }
// throw new ParseException("Unable to parse range", 0);
// }
//
// /**
// * A class representing a range within content.
// */
// static public class ContentRange {
// public long start;
// public long end;
// public int length;
//
// public ContentRange(long start, long end) {
// this.start = start;
// this.end = end;
// this.length = (int)(end - start + 1);
// }
// }
// }
| import com.whizzosoftware.hobson.bootstrap.util.HttpUtil;
import org.junit.Test;
import java.text.ParseException;
import static org.junit.Assert.*; | /*******************************************************************************
* Copyright (c) 2014 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.whizzosoftware.hobson.bootstrap.api.util;
public class HttpUtilTest {
@Test
public void testCreateRange() throws ParseException { | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/HttpUtil.java
// public class HttpUtil {
//
// /**
// * Create a ContentRange object for start and end values.
// *
// * @param start the start of the range
// * @param end the end of the range
// *
// * @return a ContentRange instance
// */
// static public ContentRange createRange(long start, long end) {
// return new ContentRange(start, end);
// }
//
// /**
// * Create a ContentRange object for an RFC-7233 Range string.
// *
// * @param range the Range string
// * @param contentLength the total length of the content
// *
// * @return a ContentRange instance (or null if the range can't be parsed)
// * @throws ParseException on failure
// */
// static public ContentRange createRange(String range, long contentLength) throws ParseException {
// if (range != null) {
// if (range.startsWith("bytes=")) {
// range = range.substring(6, range.length());
// int ix = range.indexOf("-");
// if (ix > -1 && range.length() > 1) {
// try {
// if (ix == 0) {
// return new ContentRange(contentLength - Long.parseLong(range.substring(ix + 1, range.length())), contentLength - 1);
// } else if (ix == range.length() - 1) {
// return new ContentRange(Long.parseLong(range.substring(0, ix)), contentLength - 1);
// } else {
// return new ContentRange(Long.parseLong(range.substring(0, ix)), Long.parseLong(range.substring(ix + 1, range.length())));
// }
// } catch (NumberFormatException ignored) {}
// }
// }
// }
// throw new ParseException("Unable to parse range", 0);
// }
//
// /**
// * A class representing a range within content.
// */
// static public class ContentRange {
// public long start;
// public long end;
// public int length;
//
// public ContentRange(long start, long end) {
// this.start = start;
// this.end = end;
// this.length = (int)(end - start + 1);
// }
// }
// }
// Path: src/test/java/com/whizzosoftware/hobson/bootstrap/api/util/HttpUtilTest.java
import com.whizzosoftware.hobson.bootstrap.util.HttpUtil;
import org.junit.Test;
import java.text.ParseException;
import static org.junit.Assert.*;
/*******************************************************************************
* Copyright (c) 2014 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.whizzosoftware.hobson.bootstrap.api.util;
public class HttpUtilTest {
@Test
public void testCreateRange() throws ParseException { | HttpUtil.ContentRange cr = HttpUtil.createRange("bytes=9500-9999", 10000); |
whizzosoftware/hobson-hub-core | src/main/java/com/whizzosoftware/hobson/bootstrap/api/device/store/MapDBDeviceStore.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
| import com.whizzosoftware.hobson.api.device.DeviceContext;
import com.whizzosoftware.hobson.api.device.HobsonDeviceDescriptor;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersistenceContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.persist.IdProvider;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.variable.DeviceVariableDescriptor;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set; | /*
*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.device.store;
public class MapDBDeviceStore implements DeviceStore {
final private DB db;
private IdProvider idProvider = new ContextPathIdProvider();
private CollectionPersister persister = new CollectionPersister(idProvider);
private CollectionPersistenceContext mctx;
public MapDBDeviceStore(File file) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
db = DBMaker.newFileDB(file)
.closeOnJvmShutdown()
.make(); | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
// Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/device/store/MapDBDeviceStore.java
import com.whizzosoftware.hobson.api.device.DeviceContext;
import com.whizzosoftware.hobson.api.device.HobsonDeviceDescriptor;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersistenceContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.persist.IdProvider;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.variable.DeviceVariableDescriptor;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/*
*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.device.store;
public class MapDBDeviceStore implements DeviceStore {
final private DB db;
private IdProvider idProvider = new ContextPathIdProvider();
private CollectionPersister persister = new CollectionPersister(idProvider);
private CollectionPersistenceContext mctx;
public MapDBDeviceStore(File file) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
db = DBMaker.newFileDB(file)
.closeOnJvmShutdown()
.make(); | mctx = new MapDBCollectionPersistenceContext(db); |
whizzosoftware/hobson-hub-core | src/main/java/com/whizzosoftware/hobson/bootstrap/api/config/MapDBConfigurationManager.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
| import com.whizzosoftware.hobson.api.config.ConfigurationManager;
import com.whizzosoftware.hobson.api.device.DeviceContext;
import com.whizzosoftware.hobson.api.executor.ExecutorManager;
import com.whizzosoftware.hobson.api.hub.HubConfigurationClass;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersistenceContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.property.PropertyContainerClassContext;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit; | /*
*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.config;
/**
* A MapDB implementation of ConfigurationManager.
*
* @author Dan Noguerol
*/
public class MapDBConfigurationManager implements ConfigurationManager {
private static final Logger logger = LoggerFactory.getLogger(MapDBConfigurationManager.class);
@Inject
volatile private ExecutorManager executorManager;
private File dbFile;
private DB db;
private CollectionPersister persister;
private CollectionPersistenceContext cpctx;
private Future housekeepingFuture;
public MapDBConfigurationManager() {
this(new File(new File(System.getProperty(ConfigurationManager.HOBSON_HOME), "data"), "com.whizzosoftware.hobson.hub.hobson-hub-core$config"));
}
public MapDBConfigurationManager(File dbFile) {
this.dbFile = dbFile;
}
public void start() {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
// make sure parent directory exists
if (!dbFile.getParentFile().exists()) {
if (!dbFile.getParentFile().mkdirs()) {
logger.error("Unable to create data directory: {}", dbFile.getParentFile());
}
}
// create the MapDB context
this.db = DBMaker.newFileDB(dbFile).closeOnJvmShutdown().make(); | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
// Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/config/MapDBConfigurationManager.java
import com.whizzosoftware.hobson.api.config.ConfigurationManager;
import com.whizzosoftware.hobson.api.device.DeviceContext;
import com.whizzosoftware.hobson.api.executor.ExecutorManager;
import com.whizzosoftware.hobson.api.hub.HubConfigurationClass;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersistenceContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.property.PropertyContainerClassContext;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/*
*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.config;
/**
* A MapDB implementation of ConfigurationManager.
*
* @author Dan Noguerol
*/
public class MapDBConfigurationManager implements ConfigurationManager {
private static final Logger logger = LoggerFactory.getLogger(MapDBConfigurationManager.class);
@Inject
volatile private ExecutorManager executorManager;
private File dbFile;
private DB db;
private CollectionPersister persister;
private CollectionPersistenceContext cpctx;
private Future housekeepingFuture;
public MapDBConfigurationManager() {
this(new File(new File(System.getProperty(ConfigurationManager.HOBSON_HOME), "data"), "com.whizzosoftware.hobson.hub.hobson-hub-core$config"));
}
public MapDBConfigurationManager(File dbFile) {
this.dbFile = dbFile;
}
public void start() {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
// make sure parent directory exists
if (!dbFile.getParentFile().exists()) {
if (!dbFile.getParentFile().mkdirs()) {
logger.error("Unable to create data directory: {}", dbFile.getParentFile());
}
}
// create the MapDB context
this.db = DBMaker.newFileDB(dbFile).closeOnJvmShutdown().make(); | this.cpctx = new MapDBCollectionPersistenceContext(db); |
whizzosoftware/hobson-hub-core | src/main/java/com/whizzosoftware/hobson/bootstrap/api/task/store/MapDBTaskStore.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
| import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersistenceContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.persist.IdProvider;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.task.HobsonTask;
import com.whizzosoftware.hobson.api.task.TaskContext;
import com.whizzosoftware.hobson.api.task.TaskHelper;
import com.whizzosoftware.hobson.api.task.TaskManager;
import com.whizzosoftware.hobson.api.task.store.TaskStore;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*; | /*
*******************************************************************************
* Copyright (c) 2015 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.task.store;
/**
* An implementation of TaskStore that uses MapDB for persistent storage.
*
* @author Dan Noguerol
*/
public class MapDBTaskStore implements TaskStore {
private static final Logger logger = LoggerFactory.getLogger(MapDBTaskStore.class);
final private DB db;
private IdProvider idProvider = new ContextPathIdProvider();
private CollectionPersister persister = new CollectionPersister(idProvider);
private CollectionPersistenceContext mctx;
public MapDBTaskStore(File file) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
db = DBMaker.newFileDB(file)
.closeOnJvmShutdown()
.make(); | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/util/MapDBCollectionPersistenceContext.java
// public class MapDBCollectionPersistenceContext implements CollectionPersistenceContext {
// private DB db;
//
// public MapDBCollectionPersistenceContext(DB db) {
// this.db = db;
// }
//
// @Override
// public void addSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// s.add(value);
// }
//
// @Override
// public Map<String, Object> getMap(String key) {
// return db.createHashMap(key).makeOrGet();
// }
//
// @Override
// public Object getMapValue(String key, String name) {
// Map map = getMap(key);
// return map.get(name);
// }
//
// @Override
// public Set<Object> getSet(String key) {
// return db.createHashSet(key).makeOrGet();
// }
//
// @Override
// public boolean hasMap(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSet(String key) {
// return db.exists(key);
// }
//
// @Override
// public boolean hasSetValue(String key, Object value) {
// Set<Object> s = getSet(key);
// return (s != null && s.contains(value));
// }
//
// @Override
// public void setMap(String key, Map<String,Object> map) {
// Map<String,Object> m = db.createHashMap(key).makeOrGet();
// m.clear();
// for (String k : map.keySet()) {
// Object v = map.get(k);
// if (v != null) {
// m.put(k, v);
// } else {
// m.remove(k);
// }
// }
// }
//
// @Override
// public void setMapValue(String key, String name, Object value) {
// Map<String,Object> map = getMap(key);
// map.put(name, value);
// }
//
// @Override
// public void setSet(String key, Set<Object> set) {
// Set<Object> s = getSet(key);
// s.clear();
// for (Object v : set) {
// s.add(v);
// }
// }
//
// @Override
// public void remove(String key) {
// db.delete(key);
// }
//
// @Override
// public void removeFromSet(String key, Object value) {
// Set<Object> set = getSet(key);
// set.remove(value);
// }
//
// @Override
// public void commit() {
// db.commit();
// }
//
// @Override
// public void close() {
// if (!db.isClosed()) {
// db.close();
// }
// }
// }
// Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/task/store/MapDBTaskStore.java
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersistenceContext;
import com.whizzosoftware.hobson.api.persist.CollectionPersister;
import com.whizzosoftware.hobson.api.persist.ContextPathIdProvider;
import com.whizzosoftware.hobson.api.persist.IdProvider;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.task.HobsonTask;
import com.whizzosoftware.hobson.api.task.TaskContext;
import com.whizzosoftware.hobson.api.task.TaskHelper;
import com.whizzosoftware.hobson.api.task.TaskManager;
import com.whizzosoftware.hobson.api.task.store.TaskStore;
import com.whizzosoftware.hobson.bootstrap.util.MapDBCollectionPersistenceContext;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
/*
*******************************************************************************
* Copyright (c) 2015 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************
*/
package com.whizzosoftware.hobson.bootstrap.api.task.store;
/**
* An implementation of TaskStore that uses MapDB for persistent storage.
*
* @author Dan Noguerol
*/
public class MapDBTaskStore implements TaskStore {
private static final Logger logger = LoggerFactory.getLogger(MapDBTaskStore.class);
final private DB db;
private IdProvider idProvider = new ContextPathIdProvider();
private CollectionPersister persister = new CollectionPersister(idProvider);
private CollectionPersistenceContext mctx;
public MapDBTaskStore(File file) {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
db = DBMaker.newFileDB(file)
.closeOnJvmShutdown()
.make(); | mctx = new MapDBCollectionPersistenceContext(db); |
whizzosoftware/hobson-hub-core | src/main/java/com/whizzosoftware/hobson/bootstrap/api/disco/OSGIDiscoManager.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/util/BundleUtil.java
// public class BundleUtil {
// static public BundleContext getBundleContext(Class clazz, String bundleSymbolicName) {
// if (bundleSymbolicName == null) {
// return FrameworkUtil.getBundle(clazz).getBundleContext();
// } else {
// for (Bundle bundle : FrameworkUtil.getBundle(clazz).getBundleContext().getBundles()) {
// if (bundleSymbolicName.equalsIgnoreCase(bundle.getSymbolicName())) {
// return bundle.getBundleContext();
// }
// }
// }
// throw new HobsonNotFoundException("Unable to find bundle with name: " + bundleSymbolicName);
// }
//
// /**
// * Retrieve the bundle for a specific symbolic name.
// *
// * @param symbolicName the symbolic name
// *
// * @return a Bundle instance (or null if not found)
// */
// static public Bundle getBundleForSymbolicName(String symbolicName) {
// // TODO: is there a better way to do this?
// for (Bundle bundle : FrameworkUtil.getBundle(BundleUtil.class).getBundleContext().getBundles()) {
// if (symbolicName.equalsIgnoreCase(bundle.getSymbolicName())) {
// return bundle;
// }
// }
// return null;
// }
//
// /**
// * Create a PluginStatus instance from an OSGi bundle state.
// *
// * @param state the bundle state
// *
// * @return a PluginStatus instance
// */
// static public PluginStatus createPluginStatusFromBundleState(int state) {
// switch (state) {
// case Bundle.ACTIVE:
// return PluginStatus.running();
// case Bundle.INSTALLED:
// case Bundle.RESOLVED:
// return PluginStatus.stopped();
// default:
// return PluginStatus.notInstalled();
// }
// }
// }
| import com.whizzosoftware.hobson.api.HobsonRuntimeException;
import com.whizzosoftware.hobson.api.disco.*;
import com.whizzosoftware.hobson.api.event.advertisement.DeviceAdvertisementEvent;
import com.whizzosoftware.hobson.api.event.EventManager;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.plugin.PluginManager;
import com.whizzosoftware.hobson.bootstrap.api.util.BundleUtil;
import org.osgi.framework.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*; | }
} catch (InvalidSyntaxException e) {
throw new HobsonRuntimeException("Error retrieving internal device advertisements", e);
}
return null;
}
@Override
public DeviceAdvertisement getInternalDeviceAdvertisement(HubContext ctx, String protocolId, String advId) {
try {
BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext();
ServiceReference[] references = context.getServiceReferences((String)null, "(&(objectClass=" + DeviceAdvertisement.class.getName() + ")(protocolId=" + protocolId + ")(id=" + advId + ")(internal=true))");
if (references != null && references.length == 1) {
return (DeviceAdvertisement)context.getService(references[0]);
}
} catch (InvalidSyntaxException e) {
throw new HobsonRuntimeException("Error retrieving internal device advertisements", e);
}
return null;
}
@Override
synchronized public void publishDeviceAdvertisement(HubContext ctx, final DeviceAdvertisement advertisement, boolean internal) {
logger.trace("Publishing device advertisement: {}", advertisement);
String fqId = advertisement.getProtocolId() + ":" + advertisement.getId();
if ((internal && !localPublishList.containsKey(fqId)) || (!internal && !localDiscoveryList.containsKey(fqId))) {
try {
// check if we've seen this advertisement before | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/util/BundleUtil.java
// public class BundleUtil {
// static public BundleContext getBundleContext(Class clazz, String bundleSymbolicName) {
// if (bundleSymbolicName == null) {
// return FrameworkUtil.getBundle(clazz).getBundleContext();
// } else {
// for (Bundle bundle : FrameworkUtil.getBundle(clazz).getBundleContext().getBundles()) {
// if (bundleSymbolicName.equalsIgnoreCase(bundle.getSymbolicName())) {
// return bundle.getBundleContext();
// }
// }
// }
// throw new HobsonNotFoundException("Unable to find bundle with name: " + bundleSymbolicName);
// }
//
// /**
// * Retrieve the bundle for a specific symbolic name.
// *
// * @param symbolicName the symbolic name
// *
// * @return a Bundle instance (or null if not found)
// */
// static public Bundle getBundleForSymbolicName(String symbolicName) {
// // TODO: is there a better way to do this?
// for (Bundle bundle : FrameworkUtil.getBundle(BundleUtil.class).getBundleContext().getBundles()) {
// if (symbolicName.equalsIgnoreCase(bundle.getSymbolicName())) {
// return bundle;
// }
// }
// return null;
// }
//
// /**
// * Create a PluginStatus instance from an OSGi bundle state.
// *
// * @param state the bundle state
// *
// * @return a PluginStatus instance
// */
// static public PluginStatus createPluginStatusFromBundleState(int state) {
// switch (state) {
// case Bundle.ACTIVE:
// return PluginStatus.running();
// case Bundle.INSTALLED:
// case Bundle.RESOLVED:
// return PluginStatus.stopped();
// default:
// return PluginStatus.notInstalled();
// }
// }
// }
// Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/disco/OSGIDiscoManager.java
import com.whizzosoftware.hobson.api.HobsonRuntimeException;
import com.whizzosoftware.hobson.api.disco.*;
import com.whizzosoftware.hobson.api.event.advertisement.DeviceAdvertisementEvent;
import com.whizzosoftware.hobson.api.event.EventManager;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.plugin.PluginManager;
import com.whizzosoftware.hobson.bootstrap.api.util.BundleUtil;
import org.osgi.framework.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
}
} catch (InvalidSyntaxException e) {
throw new HobsonRuntimeException("Error retrieving internal device advertisements", e);
}
return null;
}
@Override
public DeviceAdvertisement getInternalDeviceAdvertisement(HubContext ctx, String protocolId, String advId) {
try {
BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext();
ServiceReference[] references = context.getServiceReferences((String)null, "(&(objectClass=" + DeviceAdvertisement.class.getName() + ")(protocolId=" + protocolId + ")(id=" + advId + ")(internal=true))");
if (references != null && references.length == 1) {
return (DeviceAdvertisement)context.getService(references[0]);
}
} catch (InvalidSyntaxException e) {
throw new HobsonRuntimeException("Error retrieving internal device advertisements", e);
}
return null;
}
@Override
synchronized public void publishDeviceAdvertisement(HubContext ctx, final DeviceAdvertisement advertisement, boolean internal) {
logger.trace("Publishing device advertisement: {}", advertisement);
String fqId = advertisement.getProtocolId() + ":" + advertisement.getId();
if ((internal && !localPublishList.containsKey(fqId)) || (!internal && !localDiscoveryList.containsKey(fqId))) {
try {
// check if we've seen this advertisement before | BundleContext context = BundleUtil.getBundleContext(getClass(), null); |
whizzosoftware/hobson-hub-core | src/main/java/com/whizzosoftware/hobson/bootstrap/api/plugin/source/OSGILocalPluginListSource.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/util/BundleUtil.java
// public class BundleUtil {
// static public BundleContext getBundleContext(Class clazz, String bundleSymbolicName) {
// if (bundleSymbolicName == null) {
// return FrameworkUtil.getBundle(clazz).getBundleContext();
// } else {
// for (Bundle bundle : FrameworkUtil.getBundle(clazz).getBundleContext().getBundles()) {
// if (bundleSymbolicName.equalsIgnoreCase(bundle.getSymbolicName())) {
// return bundle.getBundleContext();
// }
// }
// }
// throw new HobsonNotFoundException("Unable to find bundle with name: " + bundleSymbolicName);
// }
//
// /**
// * Retrieve the bundle for a specific symbolic name.
// *
// * @param symbolicName the symbolic name
// *
// * @return a Bundle instance (or null if not found)
// */
// static public Bundle getBundleForSymbolicName(String symbolicName) {
// // TODO: is there a better way to do this?
// for (Bundle bundle : FrameworkUtil.getBundle(BundleUtil.class).getBundleContext().getBundles()) {
// if (symbolicName.equalsIgnoreCase(bundle.getSymbolicName())) {
// return bundle;
// }
// }
// return null;
// }
//
// /**
// * Create a PluginStatus instance from an OSGi bundle state.
// *
// * @param state the bundle state
// *
// * @return a PluginStatus instance
// */
// static public PluginStatus createPluginStatusFromBundleState(int state) {
// switch (state) {
// case Bundle.ACTIVE:
// return PluginStatus.running();
// case Bundle.INSTALLED:
// case Bundle.RESOLVED:
// return PluginStatus.stopped();
// default:
// return PluginStatus.notInstalled();
// }
// }
// }
| import com.whizzosoftware.hobson.api.plugin.*;
import com.whizzosoftware.hobson.bootstrap.api.util.BundleUtil;
import org.osgi.framework.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*; |
return resultMap;
}
@Override
public Collection<HobsonPluginDescriptor> getPlugin(PluginContext ctx) {
for (Bundle bundle : bundleContext.getBundles()) {
if (ctx.getPluginId().equals(bundle.getSymbolicName())) {
HobsonPlugin plugin = com.whizzosoftware.hobson.bootstrap.api.plugin.PluginUtil.getPlugin(bundle.getBundleContext(), ctx.getPluginId());
if (plugin != null) {
return Collections.singletonList((HobsonPluginDescriptor)plugin.getDescriptor());
}
}
}
return null;
}
protected HobsonPluginDescriptor createPluginDescriptor(Bundle bundle, String pluginId) {
String name = createDisplayNameFromSymbolicName(bundle.getHeaders(), bundle.getSymbolicName());
PluginType pluginType = PluginType.FRAMEWORK;
// determine if this is any sort of Hobson plugin
Dictionary headers = bundle.getHeaders();
if (isCorePlugin(headers)) {
pluginType = PluginType.CORE;
} else if (isPlugin(headers)) {
pluginType = PluginType.PLUGIN;
}
| // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/util/BundleUtil.java
// public class BundleUtil {
// static public BundleContext getBundleContext(Class clazz, String bundleSymbolicName) {
// if (bundleSymbolicName == null) {
// return FrameworkUtil.getBundle(clazz).getBundleContext();
// } else {
// for (Bundle bundle : FrameworkUtil.getBundle(clazz).getBundleContext().getBundles()) {
// if (bundleSymbolicName.equalsIgnoreCase(bundle.getSymbolicName())) {
// return bundle.getBundleContext();
// }
// }
// }
// throw new HobsonNotFoundException("Unable to find bundle with name: " + bundleSymbolicName);
// }
//
// /**
// * Retrieve the bundle for a specific symbolic name.
// *
// * @param symbolicName the symbolic name
// *
// * @return a Bundle instance (or null if not found)
// */
// static public Bundle getBundleForSymbolicName(String symbolicName) {
// // TODO: is there a better way to do this?
// for (Bundle bundle : FrameworkUtil.getBundle(BundleUtil.class).getBundleContext().getBundles()) {
// if (symbolicName.equalsIgnoreCase(bundle.getSymbolicName())) {
// return bundle;
// }
// }
// return null;
// }
//
// /**
// * Create a PluginStatus instance from an OSGi bundle state.
// *
// * @param state the bundle state
// *
// * @return a PluginStatus instance
// */
// static public PluginStatus createPluginStatusFromBundleState(int state) {
// switch (state) {
// case Bundle.ACTIVE:
// return PluginStatus.running();
// case Bundle.INSTALLED:
// case Bundle.RESOLVED:
// return PluginStatus.stopped();
// default:
// return PluginStatus.notInstalled();
// }
// }
// }
// Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/plugin/source/OSGILocalPluginListSource.java
import com.whizzosoftware.hobson.api.plugin.*;
import com.whizzosoftware.hobson.bootstrap.api.util.BundleUtil;
import org.osgi.framework.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
return resultMap;
}
@Override
public Collection<HobsonPluginDescriptor> getPlugin(PluginContext ctx) {
for (Bundle bundle : bundleContext.getBundles()) {
if (ctx.getPluginId().equals(bundle.getSymbolicName())) {
HobsonPlugin plugin = com.whizzosoftware.hobson.bootstrap.api.plugin.PluginUtil.getPlugin(bundle.getBundleContext(), ctx.getPluginId());
if (plugin != null) {
return Collections.singletonList((HobsonPluginDescriptor)plugin.getDescriptor());
}
}
}
return null;
}
protected HobsonPluginDescriptor createPluginDescriptor(Bundle bundle, String pluginId) {
String name = createDisplayNameFromSymbolicName(bundle.getHeaders(), bundle.getSymbolicName());
PluginType pluginType = PluginType.FRAMEWORK;
// determine if this is any sort of Hobson plugin
Dictionary headers = bundle.getHeaders();
if (isCorePlugin(headers)) {
pluginType = PluginType.CORE;
} else if (isPlugin(headers)) {
pluginType = PluginType.PLUGIN;
}
| PluginStatus status = BundleUtil.createPluginStatusFromBundleState(bundle.getState()); |
whizzosoftware/hobson-hub-core | src/main/java/com/whizzosoftware/hobson/bootstrap/api/event/OSGIEventManager.java | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/util/EventUtil.java
// public class EventUtil {
// public static final String PROP_EVENT_ID = "eventId";
//
// static public Event createEventFromHobsonEvent(HobsonEvent event) {
// Map map = new HashMap();
// map.put(PROP_EVENT_ID, event.getEventId());
//
// // copy over all event-specific properties
// Map propMap = event.getProperties();
// if (propMap != null) {
// for (Object key : propMap.keySet()) {
// map.put(key, propMap.get(key));
// }
// }
//
// return new Event(EventTopics.GLOBAL, map);
// }
//
// static public Map<String,Object> createMapFromEvent(Event event) {
// Map<String,Object> map = new HashMap<>();
// for (String key : event.getPropertyNames()) {
// map.put(key, event.getProperty(key));
// }
// return map;
// }
// }
| import com.whizzosoftware.hobson.api.event.*;
import com.whizzosoftware.hobson.api.event.advertisement.DeviceAdvertisementEvent;
import com.whizzosoftware.hobson.api.event.device.*;
import com.whizzosoftware.hobson.api.event.hub.HubConfigurationUpdateEvent;
import com.whizzosoftware.hobson.api.event.plugin.PluginConfigurationUpdateEvent;
import com.whizzosoftware.hobson.api.event.plugin.PluginStatusChangeEvent;
import com.whizzosoftware.hobson.api.event.presence.PresenceUpdateNotificationEvent;
import com.whizzosoftware.hobson.api.event.presence.PresenceUpdateRequestEvent;
import com.whizzosoftware.hobson.api.event.task.*;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.bootstrap.api.util.EventUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map; | Hashtable ht = new Hashtable();
ht.put(EventConstants.EVENT_TOPIC, EventTopics.GLOBAL);
synchronized (serviceRegMap) {
if (serviceRegMap.containsKey(listener)) {
serviceRegMap.get(listener).unregister();
}
Bundle bundle = FrameworkUtil.getBundle(getClass());
if (bundle != null) {
BundleContext context = bundle.getBundleContext();
if (context != null) {
ServiceRegistration sr = context.registerService(EventHandler.class.getName(), new EventHandlerAdapter(eventFactory, listener, invoker), ht);
if (sr != null) {
serviceRegMap.put(listener, sr);
} else {
logger.error("Received null service registration registering listener: " + listener);
}
}
}
}
}
@Override
public void removeListener(HubContext ctx, Object listener) {
// TODO
}
@Override
public void postEvent(HubContext ctx, HobsonEvent event) {
logger.trace("Posting event for {}: {}", ctx, event); | // Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/util/EventUtil.java
// public class EventUtil {
// public static final String PROP_EVENT_ID = "eventId";
//
// static public Event createEventFromHobsonEvent(HobsonEvent event) {
// Map map = new HashMap();
// map.put(PROP_EVENT_ID, event.getEventId());
//
// // copy over all event-specific properties
// Map propMap = event.getProperties();
// if (propMap != null) {
// for (Object key : propMap.keySet()) {
// map.put(key, propMap.get(key));
// }
// }
//
// return new Event(EventTopics.GLOBAL, map);
// }
//
// static public Map<String,Object> createMapFromEvent(Event event) {
// Map<String,Object> map = new HashMap<>();
// for (String key : event.getPropertyNames()) {
// map.put(key, event.getProperty(key));
// }
// return map;
// }
// }
// Path: src/main/java/com/whizzosoftware/hobson/bootstrap/api/event/OSGIEventManager.java
import com.whizzosoftware.hobson.api.event.*;
import com.whizzosoftware.hobson.api.event.advertisement.DeviceAdvertisementEvent;
import com.whizzosoftware.hobson.api.event.device.*;
import com.whizzosoftware.hobson.api.event.hub.HubConfigurationUpdateEvent;
import com.whizzosoftware.hobson.api.event.plugin.PluginConfigurationUpdateEvent;
import com.whizzosoftware.hobson.api.event.plugin.PluginStatusChangeEvent;
import com.whizzosoftware.hobson.api.event.presence.PresenceUpdateNotificationEvent;
import com.whizzosoftware.hobson.api.event.presence.PresenceUpdateRequestEvent;
import com.whizzosoftware.hobson.api.event.task.*;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.bootstrap.api.util.EventUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
Hashtable ht = new Hashtable();
ht.put(EventConstants.EVENT_TOPIC, EventTopics.GLOBAL);
synchronized (serviceRegMap) {
if (serviceRegMap.containsKey(listener)) {
serviceRegMap.get(listener).unregister();
}
Bundle bundle = FrameworkUtil.getBundle(getClass());
if (bundle != null) {
BundleContext context = bundle.getBundleContext();
if (context != null) {
ServiceRegistration sr = context.registerService(EventHandler.class.getName(), new EventHandlerAdapter(eventFactory, listener, invoker), ht);
if (sr != null) {
serviceRegMap.put(listener, sr);
} else {
logger.error("Received null service registration registering listener: " + listener);
}
}
}
}
}
@Override
public void removeListener(HubContext ctx, Object listener) {
// TODO
}
@Override
public void postEvent(HubContext ctx, HobsonEvent event) {
logger.trace("Posting event for {}: {}", ctx, event); | eventAdmin.postEvent(EventUtil.createEventFromHobsonEvent(event)); |
karsany/obridge | obridge-main/src/test/java/org/obridge/generators/EntityObjectGeneratorTest.java | // Path: obridge-main/src/test/java/org/obridge/BaseTest.java
// public abstract class BaseTest {
//
// private static boolean flywayInitialized = false;
// protected OracleDataSource ds;
// protected String connectionString;
// private Properties p;
//
// @Before
// public void init() throws IOException, SQLException {
// if (ds == null) {
// p = new Properties();
// p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
// connectionString = p.getProperty("connectionString");
// ds = new OracleDataSource();
// ds.setURL(connectionString);
// }
//
// if (!flywayInitialized) {
// Flyway load = Flyway.configure().dataSource(this.ds).load();
// load.clean();
// load.migrate();
// flywayInitialized = true;
// }
//
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
| import org.junit.Test;
import org.obridge.BaseTest;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException; | package org.obridge.generators;
public class EntityObjectGeneratorTest extends BaseTest {
@Test
public void testGenerate() throws IOException, PropertyVetoException, SQLException { | // Path: obridge-main/src/test/java/org/obridge/BaseTest.java
// public abstract class BaseTest {
//
// private static boolean flywayInitialized = false;
// protected OracleDataSource ds;
// protected String connectionString;
// private Properties p;
//
// @Before
// public void init() throws IOException, SQLException {
// if (ds == null) {
// p = new Properties();
// p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
// connectionString = p.getProperty("connectionString");
// ds = new OracleDataSource();
// ds.setURL(connectionString);
// }
//
// if (!flywayInitialized) {
// Flyway load = Flyway.configure().dataSource(this.ds).load();
// load.clean();
// load.migrate();
// flywayInitialized = true;
// }
//
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
// Path: obridge-main/src/test/java/org/obridge/generators/EntityObjectGeneratorTest.java
import org.junit.Test;
import org.obridge.BaseTest;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
package org.obridge.generators;
public class EntityObjectGeneratorTest extends BaseTest {
@Test
public void testGenerate() throws IOException, PropertyVetoException, SQLException { | OBridgeConfiguration c = new OBridgeConfiguration(); |
karsany/obridge | obridge-main/src/test/java/org/obridge/generators/EntityObjectGeneratorTest.java | // Path: obridge-main/src/test/java/org/obridge/BaseTest.java
// public abstract class BaseTest {
//
// private static boolean flywayInitialized = false;
// protected OracleDataSource ds;
// protected String connectionString;
// private Properties p;
//
// @Before
// public void init() throws IOException, SQLException {
// if (ds == null) {
// p = new Properties();
// p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
// connectionString = p.getProperty("connectionString");
// ds = new OracleDataSource();
// ds.setURL(connectionString);
// }
//
// if (!flywayInitialized) {
// Flyway load = Flyway.configure().dataSource(this.ds).load();
// load.clean();
// load.migrate();
// flywayInitialized = true;
// }
//
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
| import org.junit.Test;
import org.obridge.BaseTest;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException; | package org.obridge.generators;
public class EntityObjectGeneratorTest extends BaseTest {
@Test
public void testGenerate() throws IOException, PropertyVetoException, SQLException {
OBridgeConfiguration c = new OBridgeConfiguration();
c.setJdbcUrl(connectionString);
c.setSourceRoot(File.createTempFile("ObjectGenerator", Long.toString(System.nanoTime())).getParentFile().toString());
c.setRootPackageName("hu.obridge.test"); | // Path: obridge-main/src/test/java/org/obridge/BaseTest.java
// public abstract class BaseTest {
//
// private static boolean flywayInitialized = false;
// protected OracleDataSource ds;
// protected String connectionString;
// private Properties p;
//
// @Before
// public void init() throws IOException, SQLException {
// if (ds == null) {
// p = new Properties();
// p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
// connectionString = p.getProperty("connectionString");
// ds = new OracleDataSource();
// ds.setURL(connectionString);
// }
//
// if (!flywayInitialized) {
// Flyway load = Flyway.configure().dataSource(this.ds).load();
// load.clean();
// load.migrate();
// flywayInitialized = true;
// }
//
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
// Path: obridge-main/src/test/java/org/obridge/generators/EntityObjectGeneratorTest.java
import org.junit.Test;
import org.obridge.BaseTest;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
package org.obridge.generators;
public class EntityObjectGeneratorTest extends BaseTest {
@Test
public void testGenerate() throws IOException, PropertyVetoException, SQLException {
OBridgeConfiguration c = new OBridgeConfiguration();
c.setJdbcUrl(connectionString);
c.setSourceRoot(File.createTempFile("ObjectGenerator", Long.toString(System.nanoTime())).getParentFile().toString());
c.setRootPackageName("hu.obridge.test"); | c.setPackages(new Packages()); |
karsany/obridge | obridge-main/src/test/java/org/obridge/util/XStreamFactoryTest.java | // Path: obridge-main/src/test/java/org/obridge/BaseTest.java
// public abstract class BaseTest {
//
// private static boolean flywayInitialized = false;
// protected OracleDataSource ds;
// protected String connectionString;
// private Properties p;
//
// @Before
// public void init() throws IOException, SQLException {
// if (ds == null) {
// p = new Properties();
// p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
// connectionString = p.getProperty("connectionString");
// ds = new OracleDataSource();
// ds.setURL(connectionString);
// }
//
// if (!flywayInitialized) {
// Flyway load = Flyway.configure().dataSource(this.ds).load();
// load.clean();
// load.migrate();
// flywayInitialized = true;
// }
//
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
| import com.thoughtworks.xstream.XStream;
import org.junit.Assert;
import org.junit.Test;
import org.obridge.BaseTest;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.io.File;
import java.io.IOException; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.obridge.util;
/**
* @author fkarsany
*/
public class XStreamFactoryTest extends BaseTest {
/**
* Test of createXStream method, of class XStreamFactory.
*/
@Test
public void testCreateXStream() throws IOException {
XStream x = XStreamFactory.createXStream();
| // Path: obridge-main/src/test/java/org/obridge/BaseTest.java
// public abstract class BaseTest {
//
// private static boolean flywayInitialized = false;
// protected OracleDataSource ds;
// protected String connectionString;
// private Properties p;
//
// @Before
// public void init() throws IOException, SQLException {
// if (ds == null) {
// p = new Properties();
// p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
// connectionString = p.getProperty("connectionString");
// ds = new OracleDataSource();
// ds.setURL(connectionString);
// }
//
// if (!flywayInitialized) {
// Flyway load = Flyway.configure().dataSource(this.ds).load();
// load.clean();
// load.migrate();
// flywayInitialized = true;
// }
//
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
// Path: obridge-main/src/test/java/org/obridge/util/XStreamFactoryTest.java
import com.thoughtworks.xstream.XStream;
import org.junit.Assert;
import org.junit.Test;
import org.obridge.BaseTest;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.io.File;
import java.io.IOException;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.obridge.util;
/**
* @author fkarsany
*/
public class XStreamFactoryTest extends BaseTest {
/**
* Test of createXStream method, of class XStreamFactory.
*/
@Test
public void testCreateXStream() throws IOException {
XStream x = XStreamFactory.createXStream();
| OBridgeConfiguration obc = new OBridgeConfiguration(); |
karsany/obridge | obridge-main/src/test/java/org/obridge/util/XStreamFactoryTest.java | // Path: obridge-main/src/test/java/org/obridge/BaseTest.java
// public abstract class BaseTest {
//
// private static boolean flywayInitialized = false;
// protected OracleDataSource ds;
// protected String connectionString;
// private Properties p;
//
// @Before
// public void init() throws IOException, SQLException {
// if (ds == null) {
// p = new Properties();
// p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
// connectionString = p.getProperty("connectionString");
// ds = new OracleDataSource();
// ds.setURL(connectionString);
// }
//
// if (!flywayInitialized) {
// Flyway load = Flyway.configure().dataSource(this.ds).load();
// load.clean();
// load.migrate();
// flywayInitialized = true;
// }
//
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
| import com.thoughtworks.xstream.XStream;
import org.junit.Assert;
import org.junit.Test;
import org.obridge.BaseTest;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.io.File;
import java.io.IOException; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.obridge.util;
/**
* @author fkarsany
*/
public class XStreamFactoryTest extends BaseTest {
/**
* Test of createXStream method, of class XStreamFactory.
*/
@Test
public void testCreateXStream() throws IOException {
XStream x = XStreamFactory.createXStream();
OBridgeConfiguration obc = new OBridgeConfiguration();
obc.setJdbcUrl(connectionString);
obc.setSourceRoot(File.createTempFile("ObjectGenerator", Long.toString(System.nanoTime())).getParentFile().toString());
obc.setRootPackageName("hu.obridge.test"); | // Path: obridge-main/src/test/java/org/obridge/BaseTest.java
// public abstract class BaseTest {
//
// private static boolean flywayInitialized = false;
// protected OracleDataSource ds;
// protected String connectionString;
// private Properties p;
//
// @Before
// public void init() throws IOException, SQLException {
// if (ds == null) {
// p = new Properties();
// p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
// connectionString = p.getProperty("connectionString");
// ds = new OracleDataSource();
// ds.setURL(connectionString);
// }
//
// if (!flywayInitialized) {
// Flyway load = Flyway.configure().dataSource(this.ds).load();
// load.clean();
// load.migrate();
// flywayInitialized = true;
// }
//
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
// Path: obridge-main/src/test/java/org/obridge/util/XStreamFactoryTest.java
import com.thoughtworks.xstream.XStream;
import org.junit.Assert;
import org.junit.Test;
import org.obridge.BaseTest;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.io.File;
import java.io.IOException;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.obridge.util;
/**
* @author fkarsany
*/
public class XStreamFactoryTest extends BaseTest {
/**
* Test of createXStream method, of class XStreamFactory.
*/
@Test
public void testCreateXStream() throws IOException {
XStream x = XStreamFactory.createXStream();
OBridgeConfiguration obc = new OBridgeConfiguration();
obc.setJdbcUrl(connectionString);
obc.setSourceRoot(File.createTempFile("ObjectGenerator", Long.toString(System.nanoTime())).getParentFile().toString());
obc.setRootPackageName("hu.obridge.test"); | obc.setPackages(new Packages()); |
karsany/obridge | obridge-main/src/main/java/org/obridge/model/data/Type.java | // Path: obridge-main/src/main/java/org/obridge/util/StringHelper.java
// public final class StringHelper {
//
// private static Set<String> javaKeywords = new HashSet<>(Arrays.asList("abstract", "continue", "for", "new",
// "switch", "assert", "default", "goto", "package", "synchronized",
// "boolean", "do", "if", "private", "this", "break", "double",
// "implements", "protected", "throw", "byte", "else", "import",
// "public", "throws", "case", "enum", "instanceof", "return",
// "transient", "catch", "extends", "int", "short", "try", "char",
// "final", "interface", "static", "void", "class", "finally", "long",
// "strictfp", "volatile", "const", "float", "native", "super", "while"));
//
// private StringHelper() {
// }
//
// public static String toCamelCase(String s) {
// if (s == null) {
// return "";
// }
// return WordUtils.capitalizeFully(s, ' ', '_').replaceAll(" ", "").replaceAll("_", "");
// }
//
// public static String toCamelCaseSmallBegin(String s) {
// if (s == null) {
// return "";
// }
// String ss = toCamelCase(s);
// return ss.substring(0, 1).toLowerCase() + ss.substring(1);
// }
//
// public static String toOracleName(String s) {
// StringBuilder result = new StringBuilder();
// String currChar;
// if (s != null && !s.isEmpty()) {
// for (int i = 0; i < s.length(); i++) {
// currChar = s.substring(i, i + 1);
// if (i != 0 && StringUtils.isAllUpperCase(currChar)) {
// result.append("_" + currChar);
// } else {
// result.append(currChar);
// }
// }
// }
// return result.toString().toUpperCase().replaceAll("\\_\\_", "_");
// }
//
// public static boolean isJavaKeyword(String s) {
// return javaKeywords.contains(s.toLowerCase());
// }
//
// public static String unJavaKeyword(String s) {
// if (isJavaKeyword(s)) {
// return "p" + s.substring(0, 1).toUpperCase() + s.substring(1);
// }
// return s;
// }
//
// }
| import org.obridge.util.StringHelper;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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 org.obridge.model.data;
/**
* Created by fkarsany on 2015.01.11..
*/
public class Type {
private String typeName;
private List<TypeAttribute> attributeList;
private String converterPackageName;
private String objectPackage;
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public List<TypeAttribute> getAttributeList() {
return attributeList;
}
public void setAttributeList(List<TypeAttribute> attributeList) {
this.attributeList = attributeList;
}
public String getJavaClassName() { | // Path: obridge-main/src/main/java/org/obridge/util/StringHelper.java
// public final class StringHelper {
//
// private static Set<String> javaKeywords = new HashSet<>(Arrays.asList("abstract", "continue", "for", "new",
// "switch", "assert", "default", "goto", "package", "synchronized",
// "boolean", "do", "if", "private", "this", "break", "double",
// "implements", "protected", "throw", "byte", "else", "import",
// "public", "throws", "case", "enum", "instanceof", "return",
// "transient", "catch", "extends", "int", "short", "try", "char",
// "final", "interface", "static", "void", "class", "finally", "long",
// "strictfp", "volatile", "const", "float", "native", "super", "while"));
//
// private StringHelper() {
// }
//
// public static String toCamelCase(String s) {
// if (s == null) {
// return "";
// }
// return WordUtils.capitalizeFully(s, ' ', '_').replaceAll(" ", "").replaceAll("_", "");
// }
//
// public static String toCamelCaseSmallBegin(String s) {
// if (s == null) {
// return "";
// }
// String ss = toCamelCase(s);
// return ss.substring(0, 1).toLowerCase() + ss.substring(1);
// }
//
// public static String toOracleName(String s) {
// StringBuilder result = new StringBuilder();
// String currChar;
// if (s != null && !s.isEmpty()) {
// for (int i = 0; i < s.length(); i++) {
// currChar = s.substring(i, i + 1);
// if (i != 0 && StringUtils.isAllUpperCase(currChar)) {
// result.append("_" + currChar);
// } else {
// result.append(currChar);
// }
// }
// }
// return result.toString().toUpperCase().replaceAll("\\_\\_", "_");
// }
//
// public static boolean isJavaKeyword(String s) {
// return javaKeywords.contains(s.toLowerCase());
// }
//
// public static String unJavaKeyword(String s) {
// if (isJavaKeyword(s)) {
// return "p" + s.substring(0, 1).toUpperCase() + s.substring(1);
// }
// return s;
// }
//
// }
// Path: obridge-main/src/main/java/org/obridge/model/data/Type.java
import org.obridge.util.StringHelper;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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 org.obridge.model.data;
/**
* Created by fkarsany on 2015.01.11..
*/
public class Type {
private String typeName;
private List<TypeAttribute> attributeList;
private String converterPackageName;
private String objectPackage;
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public List<TypeAttribute> getAttributeList() {
return attributeList;
}
public void setAttributeList(List<TypeAttribute> attributeList) {
this.attributeList = attributeList;
}
public String getJavaClassName() { | return StringHelper.toCamelCase(typeName); |
karsany/obridge | obridge-main/src/main/java/org/obridge/model/data/OraclePackage.java | // Path: obridge-main/src/main/java/org/obridge/util/StringHelper.java
// public final class StringHelper {
//
// private static Set<String> javaKeywords = new HashSet<>(Arrays.asList("abstract", "continue", "for", "new",
// "switch", "assert", "default", "goto", "package", "synchronized",
// "boolean", "do", "if", "private", "this", "break", "double",
// "implements", "protected", "throw", "byte", "else", "import",
// "public", "throws", "case", "enum", "instanceof", "return",
// "transient", "catch", "extends", "int", "short", "try", "char",
// "final", "interface", "static", "void", "class", "finally", "long",
// "strictfp", "volatile", "const", "float", "native", "super", "while"));
//
// private StringHelper() {
// }
//
// public static String toCamelCase(String s) {
// if (s == null) {
// return "";
// }
// return WordUtils.capitalizeFully(s, ' ', '_').replaceAll(" ", "").replaceAll("_", "");
// }
//
// public static String toCamelCaseSmallBegin(String s) {
// if (s == null) {
// return "";
// }
// String ss = toCamelCase(s);
// return ss.substring(0, 1).toLowerCase() + ss.substring(1);
// }
//
// public static String toOracleName(String s) {
// StringBuilder result = new StringBuilder();
// String currChar;
// if (s != null && !s.isEmpty()) {
// for (int i = 0; i < s.length(); i++) {
// currChar = s.substring(i, i + 1);
// if (i != 0 && StringUtils.isAllUpperCase(currChar)) {
// result.append("_" + currChar);
// } else {
// result.append(currChar);
// }
// }
// }
// return result.toString().toUpperCase().replaceAll("\\_\\_", "_");
// }
//
// public static boolean isJavaKeyword(String s) {
// return javaKeywords.contains(s.toLowerCase());
// }
//
// public static String unJavaKeyword(String s) {
// if (isJavaKeyword(s)) {
// return "p" + s.substring(0, 1).toUpperCase() + s.substring(1);
// }
// return s;
// }
//
// }
| import org.obridge.util.StringHelper;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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 org.obridge.model.data;
/**
* Created by fkarsany on 2015.01.05..
*/
public class OraclePackage {
private String name;
private List<Procedure> procedureList;
private String javaPackageName;
private String contextPackage;
private String converterPackage;
private String objectPackage;
private String loggingInitializer;
private String loggingMethod;
public List<Procedure> getProcedureList() {
return procedureList;
}
public void setProcedureList(List<Procedure> procedureList) {
this.procedureList = procedureList;
}
public void setName(String name) {
this.name = name;
}
public String getJavaClassName() { | // Path: obridge-main/src/main/java/org/obridge/util/StringHelper.java
// public final class StringHelper {
//
// private static Set<String> javaKeywords = new HashSet<>(Arrays.asList("abstract", "continue", "for", "new",
// "switch", "assert", "default", "goto", "package", "synchronized",
// "boolean", "do", "if", "private", "this", "break", "double",
// "implements", "protected", "throw", "byte", "else", "import",
// "public", "throws", "case", "enum", "instanceof", "return",
// "transient", "catch", "extends", "int", "short", "try", "char",
// "final", "interface", "static", "void", "class", "finally", "long",
// "strictfp", "volatile", "const", "float", "native", "super", "while"));
//
// private StringHelper() {
// }
//
// public static String toCamelCase(String s) {
// if (s == null) {
// return "";
// }
// return WordUtils.capitalizeFully(s, ' ', '_').replaceAll(" ", "").replaceAll("_", "");
// }
//
// public static String toCamelCaseSmallBegin(String s) {
// if (s == null) {
// return "";
// }
// String ss = toCamelCase(s);
// return ss.substring(0, 1).toLowerCase() + ss.substring(1);
// }
//
// public static String toOracleName(String s) {
// StringBuilder result = new StringBuilder();
// String currChar;
// if (s != null && !s.isEmpty()) {
// for (int i = 0; i < s.length(); i++) {
// currChar = s.substring(i, i + 1);
// if (i != 0 && StringUtils.isAllUpperCase(currChar)) {
// result.append("_" + currChar);
// } else {
// result.append(currChar);
// }
// }
// }
// return result.toString().toUpperCase().replaceAll("\\_\\_", "_");
// }
//
// public static boolean isJavaKeyword(String s) {
// return javaKeywords.contains(s.toLowerCase());
// }
//
// public static String unJavaKeyword(String s) {
// if (isJavaKeyword(s)) {
// return "p" + s.substring(0, 1).toUpperCase() + s.substring(1);
// }
// return s;
// }
//
// }
// Path: obridge-main/src/main/java/org/obridge/model/data/OraclePackage.java
import org.obridge.util.StringHelper;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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 org.obridge.model.data;
/**
* Created by fkarsany on 2015.01.05..
*/
public class OraclePackage {
private String name;
private List<Procedure> procedureList;
private String javaPackageName;
private String contextPackage;
private String converterPackage;
private String objectPackage;
private String loggingInitializer;
private String loggingMethod;
public List<Procedure> getProcedureList() {
return procedureList;
}
public void setProcedureList(List<Procedure> procedureList) {
this.procedureList = procedureList;
}
public void setName(String name) {
this.name = name;
}
public String getJavaClassName() { | return StringHelper.toCamelCase(name); |
karsany/obridge | obridge-main/src/test/java/org/obridge/OBridgeTest.java | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
| import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.io.File;
import java.io.IOException;
import java.util.Properties; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.obridge;
/**
* @author fkarsany
*/
public class OBridgeTest {
@Rule
public TemporaryFolder tempdir = new TemporaryFolder();
public OBridgeTest() {
}
@Test
public void testMain() {
OBridge.main("-h");
OBridge.main("-v");
}
@Test
public void fullTest() throws IOException, InterruptedException {
Properties p = new Properties();
p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
| // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
// Path: obridge-main/src/test/java/org/obridge/OBridgeTest.java
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.obridge;
/**
* @author fkarsany
*/
public class OBridgeTest {
@Rule
public TemporaryFolder tempdir = new TemporaryFolder();
public OBridgeTest() {
}
@Test
public void testMain() {
OBridge.main("-h");
OBridge.main("-v");
}
@Test
public void fullTest() throws IOException, InterruptedException {
Properties p = new Properties();
p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
| OBridgeConfiguration oBridgeConfiguration = new OBridgeConfiguration(); |
karsany/obridge | obridge-main/src/test/java/org/obridge/OBridgeTest.java | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
| import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.io.File;
import java.io.IOException;
import java.util.Properties; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.obridge;
/**
* @author fkarsany
*/
public class OBridgeTest {
@Rule
public TemporaryFolder tempdir = new TemporaryFolder();
public OBridgeTest() {
}
@Test
public void testMain() {
OBridge.main("-h");
OBridge.main("-v");
}
@Test
public void fullTest() throws IOException, InterruptedException {
Properties p = new Properties();
p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
OBridgeConfiguration oBridgeConfiguration = new OBridgeConfiguration();
oBridgeConfiguration.setJdbcUrl(p.getProperty("connectionString")); | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/context/Packages.java
// public class Packages {
//
// private String entityObjects = "objects";
// private String converterObjects = "converters";
// private String procedureContextObjects = "context";
// private String packageObjects = "packages";
//
// public String getEntityObjects() {
// return entityObjects;
// }
//
// public void setEntityObjects(String entityObjects) {
// this.entityObjects = entityObjects;
// }
//
// public String getConverterObjects() {
// return converterObjects;
// }
//
// public void setConverterObjects(String converterObjects) {
// this.converterObjects = converterObjects;
// }
//
// public String getProcedureContextObjects() {
// return procedureContextObjects;
// }
//
// public void setProcedureContextObjects(String procedureContextObjects) {
// this.procedureContextObjects = procedureContextObjects;
// }
//
// public String getPackageObjects() {
// return packageObjects;
// }
//
// public void setPackageObjects(String packageObjects) {
// this.packageObjects = packageObjects;
// }
//
// }
// Path: obridge-main/src/test/java/org/obridge/OBridgeTest.java
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.context.Packages;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.obridge;
/**
* @author fkarsany
*/
public class OBridgeTest {
@Rule
public TemporaryFolder tempdir = new TemporaryFolder();
public OBridgeTest() {
}
@Test
public void testMain() {
OBridge.main("-h");
OBridge.main("-v");
}
@Test
public void fullTest() throws IOException, InterruptedException {
Properties p = new Properties();
p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties"));
OBridgeConfiguration oBridgeConfiguration = new OBridgeConfiguration();
oBridgeConfiguration.setJdbcUrl(p.getProperty("connectionString")); | oBridgeConfiguration.setPackages(new Packages()); |
karsany/obridge | obridge-main/src/test/java/org/obridge/util/MustacheRunnerTest.java | // Path: obridge-main/src/main/java/org/obridge/model/generator/Pojo.java
// public class Pojo {
//
// private String packageName;
// private String className;
// private List<PojoField> fields;
// private String comment;
// private List<String> imports;
// private String generatorName;
//
// public List<String> getImports() {
// return imports;
// }
//
// public void setImports(List<String> imports) {
// this.imports = imports;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public List<PojoField> getFields() {
// return fields;
// }
//
// public void setFields(List<PojoField> fields) {
// this.fields = fields;
// }
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public String getPackageName() {
// return packageName;
// }
//
// public void setPackageName(String packageName) {
// this.packageName = packageName;
// }
//
// public String getGeneratorName() {
// return generatorName;
// }
//
// public void setGeneratorName(String generatorName) {
// this.generatorName = generatorName;
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/model/generator/PojoField.java
// public class PojoField {
//
// private String fieldName;
// private String fieldType;
// private boolean readonly;
//
// public String getFieldName() {
// return fieldName;
// }
//
// public void setFieldName(String fieldName) {
// this.fieldName = fieldName;
// }
//
// public String getFieldNameInitCap() {
// return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
// }
//
// public String getFieldType() {
// return fieldType;
// }
//
// public void setFieldType(String fieldType) {
// this.fieldType = fieldType;
// }
//
// public boolean isReadonly() {
// return readonly;
// }
//
// public void setReadonly(boolean readonly) {
// this.readonly = readonly;
// }
//
// public boolean isSettable() {
// return !isReadonly();
// }
//
// }
| import org.junit.Assert;
import org.junit.Test;
import org.obridge.model.generator.Pojo;
import org.obridge.model.generator.PojoField;
import java.util.ArrayList;
import java.util.logging.Logger; | package org.obridge.util;
public class MustacheRunnerTest {
public static final String COMMENT = "This is a comment";
public static final String PACKAGE_NAME = "hu.karsany.tesztpackage";
private final static String CLASS_NAME = "ExampleClass";
@Test
public void pojoMustacheTest() {
| // Path: obridge-main/src/main/java/org/obridge/model/generator/Pojo.java
// public class Pojo {
//
// private String packageName;
// private String className;
// private List<PojoField> fields;
// private String comment;
// private List<String> imports;
// private String generatorName;
//
// public List<String> getImports() {
// return imports;
// }
//
// public void setImports(List<String> imports) {
// this.imports = imports;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public List<PojoField> getFields() {
// return fields;
// }
//
// public void setFields(List<PojoField> fields) {
// this.fields = fields;
// }
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public String getPackageName() {
// return packageName;
// }
//
// public void setPackageName(String packageName) {
// this.packageName = packageName;
// }
//
// public String getGeneratorName() {
// return generatorName;
// }
//
// public void setGeneratorName(String generatorName) {
// this.generatorName = generatorName;
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/model/generator/PojoField.java
// public class PojoField {
//
// private String fieldName;
// private String fieldType;
// private boolean readonly;
//
// public String getFieldName() {
// return fieldName;
// }
//
// public void setFieldName(String fieldName) {
// this.fieldName = fieldName;
// }
//
// public String getFieldNameInitCap() {
// return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
// }
//
// public String getFieldType() {
// return fieldType;
// }
//
// public void setFieldType(String fieldType) {
// this.fieldType = fieldType;
// }
//
// public boolean isReadonly() {
// return readonly;
// }
//
// public void setReadonly(boolean readonly) {
// this.readonly = readonly;
// }
//
// public boolean isSettable() {
// return !isReadonly();
// }
//
// }
// Path: obridge-main/src/test/java/org/obridge/util/MustacheRunnerTest.java
import org.junit.Assert;
import org.junit.Test;
import org.obridge.model.generator.Pojo;
import org.obridge.model.generator.PojoField;
import java.util.ArrayList;
import java.util.logging.Logger;
package org.obridge.util;
public class MustacheRunnerTest {
public static final String COMMENT = "This is a comment";
public static final String PACKAGE_NAME = "hu.karsany.tesztpackage";
private final static String CLASS_NAME = "ExampleClass";
@Test
public void pojoMustacheTest() {
| Pojo pojo = new Pojo(); |
karsany/obridge | obridge-main/src/test/java/org/obridge/util/MustacheRunnerTest.java | // Path: obridge-main/src/main/java/org/obridge/model/generator/Pojo.java
// public class Pojo {
//
// private String packageName;
// private String className;
// private List<PojoField> fields;
// private String comment;
// private List<String> imports;
// private String generatorName;
//
// public List<String> getImports() {
// return imports;
// }
//
// public void setImports(List<String> imports) {
// this.imports = imports;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public List<PojoField> getFields() {
// return fields;
// }
//
// public void setFields(List<PojoField> fields) {
// this.fields = fields;
// }
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public String getPackageName() {
// return packageName;
// }
//
// public void setPackageName(String packageName) {
// this.packageName = packageName;
// }
//
// public String getGeneratorName() {
// return generatorName;
// }
//
// public void setGeneratorName(String generatorName) {
// this.generatorName = generatorName;
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/model/generator/PojoField.java
// public class PojoField {
//
// private String fieldName;
// private String fieldType;
// private boolean readonly;
//
// public String getFieldName() {
// return fieldName;
// }
//
// public void setFieldName(String fieldName) {
// this.fieldName = fieldName;
// }
//
// public String getFieldNameInitCap() {
// return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
// }
//
// public String getFieldType() {
// return fieldType;
// }
//
// public void setFieldType(String fieldType) {
// this.fieldType = fieldType;
// }
//
// public boolean isReadonly() {
// return readonly;
// }
//
// public void setReadonly(boolean readonly) {
// this.readonly = readonly;
// }
//
// public boolean isSettable() {
// return !isReadonly();
// }
//
// }
| import org.junit.Assert;
import org.junit.Test;
import org.obridge.model.generator.Pojo;
import org.obridge.model.generator.PojoField;
import java.util.ArrayList;
import java.util.logging.Logger; | package org.obridge.util;
public class MustacheRunnerTest {
public static final String COMMENT = "This is a comment";
public static final String PACKAGE_NAME = "hu.karsany.tesztpackage";
private final static String CLASS_NAME = "ExampleClass";
@Test
public void pojoMustacheTest() {
Pojo pojo = new Pojo();
pojo.setClassName(CLASS_NAME);
pojo.setComment(COMMENT);
pojo.setPackageName(PACKAGE_NAME); | // Path: obridge-main/src/main/java/org/obridge/model/generator/Pojo.java
// public class Pojo {
//
// private String packageName;
// private String className;
// private List<PojoField> fields;
// private String comment;
// private List<String> imports;
// private String generatorName;
//
// public List<String> getImports() {
// return imports;
// }
//
// public void setImports(List<String> imports) {
// this.imports = imports;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public List<PojoField> getFields() {
// return fields;
// }
//
// public void setFields(List<PojoField> fields) {
// this.fields = fields;
// }
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public String getPackageName() {
// return packageName;
// }
//
// public void setPackageName(String packageName) {
// this.packageName = packageName;
// }
//
// public String getGeneratorName() {
// return generatorName;
// }
//
// public void setGeneratorName(String generatorName) {
// this.generatorName = generatorName;
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/model/generator/PojoField.java
// public class PojoField {
//
// private String fieldName;
// private String fieldType;
// private boolean readonly;
//
// public String getFieldName() {
// return fieldName;
// }
//
// public void setFieldName(String fieldName) {
// this.fieldName = fieldName;
// }
//
// public String getFieldNameInitCap() {
// return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
// }
//
// public String getFieldType() {
// return fieldType;
// }
//
// public void setFieldType(String fieldType) {
// this.fieldType = fieldType;
// }
//
// public boolean isReadonly() {
// return readonly;
// }
//
// public void setReadonly(boolean readonly) {
// this.readonly = readonly;
// }
//
// public boolean isSettable() {
// return !isReadonly();
// }
//
// }
// Path: obridge-main/src/test/java/org/obridge/util/MustacheRunnerTest.java
import org.junit.Assert;
import org.junit.Test;
import org.obridge.model.generator.Pojo;
import org.obridge.model.generator.PojoField;
import java.util.ArrayList;
import java.util.logging.Logger;
package org.obridge.util;
public class MustacheRunnerTest {
public static final String COMMENT = "This is a comment";
public static final String PACKAGE_NAME = "hu.karsany.tesztpackage";
private final static String CLASS_NAME = "ExampleClass";
@Test
public void pojoMustacheTest() {
Pojo pojo = new Pojo();
pojo.setClassName(CLASS_NAME);
pojo.setComment(COMMENT);
pojo.setPackageName(PACKAGE_NAME); | pojo.setFields(new ArrayList<PojoField>()); |
karsany/obridge | obridge-main/src/main/java/org/obridge/util/XStreamFactory.java | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
| import com.thoughtworks.xstream.XStream;
import org.obridge.context.OBridgeConfiguration; | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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 org.obridge.util;
/**
* @author fkarsany
*/
public class XStreamFactory {
private XStreamFactory() {
}
public static XStream createXStream() {
XStream xStream = new XStream();
| // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
// Path: obridge-main/src/main/java/org/obridge/util/XStreamFactory.java
import com.thoughtworks.xstream.XStream;
import org.obridge.context.OBridgeConfiguration;
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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 org.obridge.util;
/**
* @author fkarsany
*/
public class XStreamFactory {
private XStreamFactory() {
}
public static XStream createXStream() {
XStream xStream = new XStream();
| xStream.alias("configuration", OBridgeConfiguration.class); |
karsany/obridge | obridge-main/src/main/java/org/obridge/generators/PopulateObjectsTable.java | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/DataSourceProvider.java
// public final class DataSourceProvider {
//
// private static Map<String, ComboPooledDataSource> dataSourcePool = null;
//
// private DataSourceProvider() {
// }
//
// public static DataSource getDataSource(String jdbcURL) throws PropertyVetoException {
//
// if (dataSourcePool == null) {
// dataSourcePool = new HashMap<>();
// }
//
// if (!dataSourcePool.containsKey(jdbcURL)) {
//
// ComboPooledDataSource dataSource = new ComboPooledDataSource();
// dataSource.setDriverClass("oracle.jdbc.OracleDriver");
// dataSource.setJdbcUrl(jdbcURL);
//
// dataSourcePool.put(jdbcURL, dataSource);
// }
//
// return dataSourcePool.get(jdbcURL);
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
| import org.obridge.context.OBridgeConfiguration;
import org.obridge.util.DataSourceProvider;
import org.obridge.util.OBridgeException;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.CallableStatement; | package org.obridge.generators;
public class PopulateObjectsTable {
public static void run(OBridgeConfiguration c) {
String sourcesTableProc = c.getSourcesTableProc();
String projectName = c.getProjectName();
if (sourcesTableProc == null) {
return;
}
sourcesTableProc = "begin " + sourcesTableProc + "(?); end;";
try { | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/DataSourceProvider.java
// public final class DataSourceProvider {
//
// private static Map<String, ComboPooledDataSource> dataSourcePool = null;
//
// private DataSourceProvider() {
// }
//
// public static DataSource getDataSource(String jdbcURL) throws PropertyVetoException {
//
// if (dataSourcePool == null) {
// dataSourcePool = new HashMap<>();
// }
//
// if (!dataSourcePool.containsKey(jdbcURL)) {
//
// ComboPooledDataSource dataSource = new ComboPooledDataSource();
// dataSource.setDriverClass("oracle.jdbc.OracleDriver");
// dataSource.setJdbcUrl(jdbcURL);
//
// dataSourcePool.put(jdbcURL, dataSource);
// }
//
// return dataSourcePool.get(jdbcURL);
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
// Path: obridge-main/src/main/java/org/obridge/generators/PopulateObjectsTable.java
import org.obridge.context.OBridgeConfiguration;
import org.obridge.util.DataSourceProvider;
import org.obridge.util.OBridgeException;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.CallableStatement;
package org.obridge.generators;
public class PopulateObjectsTable {
public static void run(OBridgeConfiguration c) {
String sourcesTableProc = c.getSourcesTableProc();
String projectName = c.getProjectName();
if (sourcesTableProc == null) {
return;
}
sourcesTableProc = "begin " + sourcesTableProc + "(?); end;";
try { | DataSource datasource = DataSourceProvider.getDataSource(c.getJdbcUrl()); |
karsany/obridge | obridge-main/src/main/java/org/obridge/generators/PopulateObjectsTable.java | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/DataSourceProvider.java
// public final class DataSourceProvider {
//
// private static Map<String, ComboPooledDataSource> dataSourcePool = null;
//
// private DataSourceProvider() {
// }
//
// public static DataSource getDataSource(String jdbcURL) throws PropertyVetoException {
//
// if (dataSourcePool == null) {
// dataSourcePool = new HashMap<>();
// }
//
// if (!dataSourcePool.containsKey(jdbcURL)) {
//
// ComboPooledDataSource dataSource = new ComboPooledDataSource();
// dataSource.setDriverClass("oracle.jdbc.OracleDriver");
// dataSource.setJdbcUrl(jdbcURL);
//
// dataSourcePool.put(jdbcURL, dataSource);
// }
//
// return dataSourcePool.get(jdbcURL);
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
| import org.obridge.context.OBridgeConfiguration;
import org.obridge.util.DataSourceProvider;
import org.obridge.util.OBridgeException;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.CallableStatement; | package org.obridge.generators;
public class PopulateObjectsTable {
public static void run(OBridgeConfiguration c) {
String sourcesTableProc = c.getSourcesTableProc();
String projectName = c.getProjectName();
if (sourcesTableProc == null) {
return;
}
sourcesTableProc = "begin " + sourcesTableProc + "(?); end;";
try {
DataSource datasource = DataSourceProvider.getDataSource(c.getJdbcUrl());
CallableStatement statement = datasource.getConnection().prepareCall(sourcesTableProc);
statement.setString(1, projectName);
statement.execute();
} catch (Exception e) { | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/DataSourceProvider.java
// public final class DataSourceProvider {
//
// private static Map<String, ComboPooledDataSource> dataSourcePool = null;
//
// private DataSourceProvider() {
// }
//
// public static DataSource getDataSource(String jdbcURL) throws PropertyVetoException {
//
// if (dataSourcePool == null) {
// dataSourcePool = new HashMap<>();
// }
//
// if (!dataSourcePool.containsKey(jdbcURL)) {
//
// ComboPooledDataSource dataSource = new ComboPooledDataSource();
// dataSource.setDriverClass("oracle.jdbc.OracleDriver");
// dataSource.setJdbcUrl(jdbcURL);
//
// dataSourcePool.put(jdbcURL, dataSource);
// }
//
// return dataSourcePool.get(jdbcURL);
// }
//
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
// Path: obridge-main/src/main/java/org/obridge/generators/PopulateObjectsTable.java
import org.obridge.context.OBridgeConfiguration;
import org.obridge.util.DataSourceProvider;
import org.obridge.util.OBridgeException;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.CallableStatement;
package org.obridge.generators;
public class PopulateObjectsTable {
public static void run(OBridgeConfiguration c) {
String sourcesTableProc = c.getSourcesTableProc();
String projectName = c.getProjectName();
if (sourcesTableProc == null) {
return;
}
sourcesTableProc = "begin " + sourcesTableProc + "(?); end;";
try {
DataSource datasource = DataSourceProvider.getDataSource(c.getJdbcUrl());
CallableStatement statement = datasource.getConnection().prepareCall(sourcesTableProc);
statement.setString(1, projectName);
statement.execute();
} catch (Exception e) { | throw new OBridgeException(e); |
karsany/obridge | obridge-main/src/main/java/org/obridge/OBridge.java | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/XStreamFactory.java
// public class XStreamFactory {
//
// private XStreamFactory() {
// }
//
// public static XStream createXStream() {
// XStream xStream = new XStream();
//
// xStream.alias("configuration", OBridgeConfiguration.class);
//
// return xStream;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.Properties;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.cli.*;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.generators.*;
import org.obridge.util.OBridgeException;
import org.obridge.util.XStreamFactory; | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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 org.obridge;
public class OBridge {
public static void main(String... args) {
try {
Options o = new Options();
CommandLine cmd = getCommandLine(o, args);
if (cmd.hasOption("h")) {
printHelp(o);
return;
}
if (cmd.hasOption("v")) {
printVersion();
return;
}
if (cmd.hasOption("c")) {
new OBridge().generate(new File(cmd.getOptionValue("c")));
} else {
printHelp(o);
}
} catch (ParseException e) { | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/XStreamFactory.java
// public class XStreamFactory {
//
// private XStreamFactory() {
// }
//
// public static XStream createXStream() {
// XStream xStream = new XStream();
//
// xStream.alias("configuration", OBridgeConfiguration.class);
//
// return xStream;
// }
//
// }
// Path: obridge-main/src/main/java/org/obridge/OBridge.java
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.cli.*;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.generators.*;
import org.obridge.util.OBridgeException;
import org.obridge.util.XStreamFactory;
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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 org.obridge;
public class OBridge {
public static void main(String... args) {
try {
Options o = new Options();
CommandLine cmd = getCommandLine(o, args);
if (cmd.hasOption("h")) {
printHelp(o);
return;
}
if (cmd.hasOption("v")) {
printVersion();
return;
}
if (cmd.hasOption("c")) {
new OBridge().generate(new File(cmd.getOptionValue("c")));
} else {
printHelp(o);
}
} catch (ParseException e) { | throw new OBridgeException("Exception in OBridge Main progam", e); |
karsany/obridge | obridge-main/src/main/java/org/obridge/OBridge.java | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/XStreamFactory.java
// public class XStreamFactory {
//
// private XStreamFactory() {
// }
//
// public static XStream createXStream() {
// XStream xStream = new XStream();
//
// xStream.alias("configuration", OBridgeConfiguration.class);
//
// return xStream;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.Properties;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.cli.*;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.generators.*;
import org.obridge.util.OBridgeException;
import org.obridge.util.XStreamFactory; | private static CommandLine getCommandLine(Options o, String[] args) throws ParseException {
o.addOption(
Option.builder("v")
.longOpt("version")
.desc("print version number")
.required(false)
.build()
);
o.addOption(
Option.builder("h")
.longOpt("help")
.desc("prints this help")
.required(false)
.build()
);
o.addOption(
Option.builder("c")
.desc("OBridge XML config file")
.longOpt("config")
.hasArg()
.argName("file")
.build()
);
CommandLineParser parser = new PosixParser();
return parser.parse(o, args);
}
| // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/XStreamFactory.java
// public class XStreamFactory {
//
// private XStreamFactory() {
// }
//
// public static XStream createXStream() {
// XStream xStream = new XStream();
//
// xStream.alias("configuration", OBridgeConfiguration.class);
//
// return xStream;
// }
//
// }
// Path: obridge-main/src/main/java/org/obridge/OBridge.java
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.cli.*;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.generators.*;
import org.obridge.util.OBridgeException;
import org.obridge.util.XStreamFactory;
private static CommandLine getCommandLine(Options o, String[] args) throws ParseException {
o.addOption(
Option.builder("v")
.longOpt("version")
.desc("print version number")
.required(false)
.build()
);
o.addOption(
Option.builder("h")
.longOpt("help")
.desc("prints this help")
.required(false)
.build()
);
o.addOption(
Option.builder("c")
.desc("OBridge XML config file")
.longOpt("config")
.hasArg()
.argName("file")
.build()
);
CommandLineParser parser = new PosixParser();
return parser.parse(o, args);
}
| public void generate(OBridgeConfiguration c) { |
karsany/obridge | obridge-main/src/main/java/org/obridge/OBridge.java | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/XStreamFactory.java
// public class XStreamFactory {
//
// private XStreamFactory() {
// }
//
// public static XStream createXStream() {
// XStream xStream = new XStream();
//
// xStream.alias("configuration", OBridgeConfiguration.class);
//
// return xStream;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.Properties;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.cli.*;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.generators.*;
import org.obridge.util.OBridgeException;
import org.obridge.util.XStreamFactory; | Option.builder("c")
.desc("OBridge XML config file")
.longOpt("config")
.hasArg()
.argName("file")
.build()
);
CommandLineParser parser = new PosixParser();
return parser.parse(o, args);
}
public void generate(OBridgeConfiguration c) {
// populate objects table
PopulateObjectsTable.run(c);
// generate objects
EntityObjectGenerator.generate(c);
// generate converters
ConverterObjectGenerator.generate(c);
// generate contexts
ProcedureContextGenerator.generate(c);
// generate packages
PackageObjectGenerator.generate(c);
}
public OBridgeConfiguration loadConfiguration(File f) { | // Path: obridge-main/src/main/java/org/obridge/context/OBridgeConfiguration.java
// public class OBridgeConfiguration {
//
// public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;
// public static final boolean ADD_ASSERT = false;
//
// private String jdbcUrl;
// private String sourceRoot;
// private String rootPackageName;
// private Packages packages;
// private Logging logging;
// private String packagesLike;
// private String sourceOwner;
// private String projectName;
// private String sourcesTableProc;
// private String sourcesTable;
//
// public String getPackagesLike() {
// if (packagesLike == null) {
// return "%";
// }
// return packagesLike;
// }
//
// public void setPackagesLike(String packagesLike) {
// this.packagesLike = packagesLike;
// }
//
// public String getSourceOwner() {
// return sourceOwner;
// }
//
// public void setSourceOwner(String sourceOwner) {
// this.sourceOwner = sourceOwner;
// }
//
// public String getJdbcUrl() {
// return jdbcUrl;
// }
//
// public void setJdbcUrl(String jdbcUrl) {
// this.jdbcUrl = jdbcUrl;
// }
//
// public String getSourceRoot() {
// return sourceRoot;
// }
//
// public void setSourceRoot(String sourceRoot) {
// this.sourceRoot = sourceRoot;
// }
//
// public String getRootPackageName() {
// return rootPackageName;
// }
//
// public void setRootPackageName(String rootPackageName) {
// this.rootPackageName = rootPackageName;
// }
//
// public Packages getPackages() {
// return packages;
// }
//
// public void setPackages(Packages packages) {
// this.packages = packages;
// }
//
// public Logging getLogging() {
// return logging;
// }
//
// public void setLogging(Logging logging) {
// this.logging = logging;
// }
//
// public String getSourcesTable() {
// return sourcesTable;
// }
//
// public void setSourcesTable(String sourcesTable) {
// this.sourcesTable = sourcesTable;
// }
//
// public String getSourcesTableProc() {
// return sourcesTableProc;
// }
//
// public String getProjectName() { return projectName == null ? "default": projectName; }
//
// public void setProjectName(String projectName) { this.projectName = projectName; }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/OBridgeException.java
// public class OBridgeException extends RuntimeException {
//
// public OBridgeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OBridgeException(Throwable cause) {
// super(cause);
// }
//
// public OBridgeException(String message) {
// super(message);
// }
// }
//
// Path: obridge-main/src/main/java/org/obridge/util/XStreamFactory.java
// public class XStreamFactory {
//
// private XStreamFactory() {
// }
//
// public static XStream createXStream() {
// XStream xStream = new XStream();
//
// xStream.alias("configuration", OBridgeConfiguration.class);
//
// return xStream;
// }
//
// }
// Path: obridge-main/src/main/java/org/obridge/OBridge.java
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.cli.*;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.generators.*;
import org.obridge.util.OBridgeException;
import org.obridge.util.XStreamFactory;
Option.builder("c")
.desc("OBridge XML config file")
.longOpt("config")
.hasArg()
.argName("file")
.build()
);
CommandLineParser parser = new PosixParser();
return parser.parse(o, args);
}
public void generate(OBridgeConfiguration c) {
// populate objects table
PopulateObjectsTable.run(c);
// generate objects
EntityObjectGenerator.generate(c);
// generate converters
ConverterObjectGenerator.generate(c);
// generate contexts
ProcedureContextGenerator.generate(c);
// generate packages
PackageObjectGenerator.generate(c);
}
public OBridgeConfiguration loadConfiguration(File f) { | XStream xs = XStreamFactory.createXStream(); |
WASdev/tool.accelerate.core | liberty-starter-application/src/test/java/com/ibm/liberty/starter/it/api/v1/DownloadProjectEndpointTest.java | // Path: liberty-starter-application/src/test/java/com/ibm/liberty/starter/it/api/v1/utils/DownloadZip.java
// public class DownloadZip {
// public static Response get(String queryString) throws Exception {
// Client client = ClientBuilder.newClient();
// String port = System.getProperty("liberty.test.port");
// String url = "http://localhost:" + port + "/start/api/v1/data?" + queryString;
// System.out.println("Testing " + url);
// Response response = client.target(url).request("application/zip").get();
// return response;
// }
//
// public static void assertBasicContent(Response resp, String buildFile, boolean bluemix) throws Exception{
// boolean foundBuildFile = false;
// boolean foundReadme = false;
// boolean foundSrc = false;
// boolean foundTests = false;
// boolean foundBluemixFiles = false;
// // Read the response into an InputStream
// InputStream entityInputStream = resp.readEntity(InputStream.class);
// // Create a new ZipInputStream from the response InputStream
// ZipInputStream zipIn = new ZipInputStream(entityInputStream);
// // This system property is being set in the liberty-starter-application/build.gradle file
// String tempDir = System.getProperty("liberty.temp.dir");
// File file = new File(tempDir + "/TestApp.zip");
// System.out.println("Creating zip file: " + file.toString());
// file.getParentFile().mkdirs();
// ZipEntry inputEntry = null;
// String zipEntries = "";
// while ((inputEntry = zipIn.getNextEntry()) != null) {
// String entryName = inputEntry.getName();
// zipEntries += entryName + ",";
// if (buildFile.equals(entryName)) {
// foundBuildFile = true;
// }
// if ("README.md".equals(entryName)) {
// foundReadme = true;
// }
// if (entryName.startsWith("src/main/java")) {
// foundSrc = true;
// }
// if (entryName.startsWith("src/test/java")) {
// foundTests = true;
// }
// if (entryName.equals("manifest.yml")) {
// foundBluemixFiles = true;
// }
// zipIn.closeEntry();
// }
// zipIn.close();
// assertTrue("Didn't find build file " + buildFile + ". Zip entries were: " + zipEntries, foundBuildFile);
// assertTrue("Didn't find README.md file. Zip entries were: " + zipEntries, foundReadme);
// assertTrue("Didn't find any Java source files i.e. files starting src/main/java. Zip entries were: " + zipEntries, foundSrc);
// assertTrue("Didn't find any Java test files i.e. files starting src/test/java. Zip entries were: " + zipEntries, foundTests);
// assertTrue("Expected foundBluemixFiles to be " + bluemix + ". Zip entries were: " + zipEntries, bluemix == foundBluemixFiles);
// }
// }
| import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import javax.ws.rs.core.Response;
import org.junit.Test;
import com.ibm.liberty.starter.it.api.v1.utils.DownloadZip; | /*******************************************************************************
* Copyright (c) 2017 IBM Corp.
*
* 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.ibm.liberty.starter.it.api.v1;
public class DownloadProjectEndpointTest {
@Test
public void generateMavenProjectTest() throws Exception {
String queryString = "tech=rest&name=Test&deploy=local"; | // Path: liberty-starter-application/src/test/java/com/ibm/liberty/starter/it/api/v1/utils/DownloadZip.java
// public class DownloadZip {
// public static Response get(String queryString) throws Exception {
// Client client = ClientBuilder.newClient();
// String port = System.getProperty("liberty.test.port");
// String url = "http://localhost:" + port + "/start/api/v1/data?" + queryString;
// System.out.println("Testing " + url);
// Response response = client.target(url).request("application/zip").get();
// return response;
// }
//
// public static void assertBasicContent(Response resp, String buildFile, boolean bluemix) throws Exception{
// boolean foundBuildFile = false;
// boolean foundReadme = false;
// boolean foundSrc = false;
// boolean foundTests = false;
// boolean foundBluemixFiles = false;
// // Read the response into an InputStream
// InputStream entityInputStream = resp.readEntity(InputStream.class);
// // Create a new ZipInputStream from the response InputStream
// ZipInputStream zipIn = new ZipInputStream(entityInputStream);
// // This system property is being set in the liberty-starter-application/build.gradle file
// String tempDir = System.getProperty("liberty.temp.dir");
// File file = new File(tempDir + "/TestApp.zip");
// System.out.println("Creating zip file: " + file.toString());
// file.getParentFile().mkdirs();
// ZipEntry inputEntry = null;
// String zipEntries = "";
// while ((inputEntry = zipIn.getNextEntry()) != null) {
// String entryName = inputEntry.getName();
// zipEntries += entryName + ",";
// if (buildFile.equals(entryName)) {
// foundBuildFile = true;
// }
// if ("README.md".equals(entryName)) {
// foundReadme = true;
// }
// if (entryName.startsWith("src/main/java")) {
// foundSrc = true;
// }
// if (entryName.startsWith("src/test/java")) {
// foundTests = true;
// }
// if (entryName.equals("manifest.yml")) {
// foundBluemixFiles = true;
// }
// zipIn.closeEntry();
// }
// zipIn.close();
// assertTrue("Didn't find build file " + buildFile + ". Zip entries were: " + zipEntries, foundBuildFile);
// assertTrue("Didn't find README.md file. Zip entries were: " + zipEntries, foundReadme);
// assertTrue("Didn't find any Java source files i.e. files starting src/main/java. Zip entries were: " + zipEntries, foundSrc);
// assertTrue("Didn't find any Java test files i.e. files starting src/test/java. Zip entries were: " + zipEntries, foundTests);
// assertTrue("Expected foundBluemixFiles to be " + bluemix + ". Zip entries were: " + zipEntries, bluemix == foundBluemixFiles);
// }
// }
// Path: liberty-starter-application/src/test/java/com/ibm/liberty/starter/it/api/v1/DownloadProjectEndpointTest.java
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import javax.ws.rs.core.Response;
import org.junit.Test;
import com.ibm.liberty.starter.it.api.v1.utils.DownloadZip;
/*******************************************************************************
* Copyright (c) 2017 IBM Corp.
*
* 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.ibm.liberty.starter.it.api.v1;
public class DownloadProjectEndpointTest {
@Test
public void generateMavenProjectTest() throws Exception {
String queryString = "tech=rest&name=Test&deploy=local"; | Response response = DownloadZip.get(queryString); |
WASdev/tool.accelerate.core | starter-microservice-template/src/test/java/com/ibm/liberty/starter/service/template/api/v1/it/TestApplication.java | // Path: liberty-starter-model/src/main/java/com/ibm/liberty/starter/api/v1/model/provider/Dependency.java
// public class Dependency {
// private Scope scope;
// private String groupId;
// private String artifactId;
// private String version;
//
// public enum Scope {
// PROVIDED, COMPILE, RUNTIME;
// }
//
// @ApiModelProperty(required = true)
// public Scope getScope() {
// return scope;
// }
//
// public void setScope(Scope scope) {
// this.scope = scope;
// }
//
// @ApiModelProperty(required = false)
// public String getGroupId() {
// return groupId;
// }
//
// public void setGroupId(String groupId) {
// this.groupId = groupId;
// }
//
// @ApiModelProperty(required = true)
// public String getArtifactId() {
// return artifactId;
// }
//
// public void setArtifactId(String artifactId) {
// this.artifactId = artifactId;
// }
//
// @ApiModelProperty(required = true)
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
//
// }
//
// Path: liberty-starter-model/src/main/java/com/ibm/liberty/starter/api/v1/model/provider/Location.java
// public class Location {
// private String path;
// private String url;
//
// public Location(String path, String url) {
// this.path = path;
// this.url = url;
// }
//
// public Location(String url) {
// this.url = url;
// }
//
// public Location() {
// //JSON serialisation
// }
//
// @ApiModelProperty(value="Relative path to insert the file within the sample project structure", required=false)
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
//
// @ApiModelProperty(value="URL to retrieve the file from", required=true)
// public String getUrl() {
// return url;
// }
// public void setUrl(String url) {
// this.url = url;
// }
//
//
// }
//
// Path: liberty-starter-model/src/main/java/com/ibm/liberty/starter/api/v1/model/provider/Provider.java
// public class Provider {
// private String description;
// private Dependency[] dependencies;
// private Location repoUrl;
//
// @ApiModelProperty(value = "Description of the technology provider to be inserted into index.html", required = true)
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// @ApiModelProperty(value = "Dependencies to be specified to the user when they get the download", required = true)
// public Dependency[] getDependencies() {
// return dependencies;
// }
//
// public void setDependencies(Dependency[] dependencies) {
// this.dependencies = dependencies;
// }
//
// @ApiModelProperty(value = "The location of the repository for this microservice.")
// public Location getRepoUrl() {
// return repoUrl;
// }
//
// public void setRepoUrl(Location repoUrl) {
// this.repoUrl = repoUrl;
// }
//
// }
//
// Path: liberty-starter-model/src/main/java/com/ibm/liberty/starter/api/v1/model/provider/Sample.java
// public class Sample {
// private String base;
// private Location[] locations;
//
// @ApiModelProperty(value="If specified, then this path will be used to create a relative path from any location URLs which do not have a path specified.", required=false)
// public String getBase() {
// return base;
// }
// public void setBase(String base) {
// this.base = base;
// }
//
// @ApiModelProperty(value="Files which make up the sample", required=true)
// public Location[] getLocations() {
// return locations;
// }
// public void setLocations(Location[] locations) {
// this.locations = locations;
// }
//
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.ibm.liberty.starter.api.v1.model.provider.Dependency;
import com.ibm.liberty.starter.api.v1.model.provider.Location;
import com.ibm.liberty.starter.api.v1.model.provider.Provider;
import com.ibm.liberty.starter.api.v1.model.provider.Sample; | /*******************************************************************************
* Copyright (c) 2016 IBM Corp.
*
* 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.ibm.liberty.starter.service.template.api.v1.it;
/**
* Test the deployed service responds as expected
*
*/
public class TestApplication extends EndpointTest {
@Before
public void checkSetup() {
checkAvailability("/api/v1/provider/");
}
@Test
public void testProvider() throws Exception { | // Path: liberty-starter-model/src/main/java/com/ibm/liberty/starter/api/v1/model/provider/Dependency.java
// public class Dependency {
// private Scope scope;
// private String groupId;
// private String artifactId;
// private String version;
//
// public enum Scope {
// PROVIDED, COMPILE, RUNTIME;
// }
//
// @ApiModelProperty(required = true)
// public Scope getScope() {
// return scope;
// }
//
// public void setScope(Scope scope) {
// this.scope = scope;
// }
//
// @ApiModelProperty(required = false)
// public String getGroupId() {
// return groupId;
// }
//
// public void setGroupId(String groupId) {
// this.groupId = groupId;
// }
//
// @ApiModelProperty(required = true)
// public String getArtifactId() {
// return artifactId;
// }
//
// public void setArtifactId(String artifactId) {
// this.artifactId = artifactId;
// }
//
// @ApiModelProperty(required = true)
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
//
// }
//
// Path: liberty-starter-model/src/main/java/com/ibm/liberty/starter/api/v1/model/provider/Location.java
// public class Location {
// private String path;
// private String url;
//
// public Location(String path, String url) {
// this.path = path;
// this.url = url;
// }
//
// public Location(String url) {
// this.url = url;
// }
//
// public Location() {
// //JSON serialisation
// }
//
// @ApiModelProperty(value="Relative path to insert the file within the sample project structure", required=false)
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
//
// @ApiModelProperty(value="URL to retrieve the file from", required=true)
// public String getUrl() {
// return url;
// }
// public void setUrl(String url) {
// this.url = url;
// }
//
//
// }
//
// Path: liberty-starter-model/src/main/java/com/ibm/liberty/starter/api/v1/model/provider/Provider.java
// public class Provider {
// private String description;
// private Dependency[] dependencies;
// private Location repoUrl;
//
// @ApiModelProperty(value = "Description of the technology provider to be inserted into index.html", required = true)
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// @ApiModelProperty(value = "Dependencies to be specified to the user when they get the download", required = true)
// public Dependency[] getDependencies() {
// return dependencies;
// }
//
// public void setDependencies(Dependency[] dependencies) {
// this.dependencies = dependencies;
// }
//
// @ApiModelProperty(value = "The location of the repository for this microservice.")
// public Location getRepoUrl() {
// return repoUrl;
// }
//
// public void setRepoUrl(Location repoUrl) {
// this.repoUrl = repoUrl;
// }
//
// }
//
// Path: liberty-starter-model/src/main/java/com/ibm/liberty/starter/api/v1/model/provider/Sample.java
// public class Sample {
// private String base;
// private Location[] locations;
//
// @ApiModelProperty(value="If specified, then this path will be used to create a relative path from any location URLs which do not have a path specified.", required=false)
// public String getBase() {
// return base;
// }
// public void setBase(String base) {
// this.base = base;
// }
//
// @ApiModelProperty(value="Files which make up the sample", required=true)
// public Location[] getLocations() {
// return locations;
// }
// public void setLocations(Location[] locations) {
// this.locations = locations;
// }
//
//
// }
// Path: starter-microservice-template/src/test/java/com/ibm/liberty/starter/service/template/api/v1/it/TestApplication.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.ibm.liberty.starter.api.v1.model.provider.Dependency;
import com.ibm.liberty.starter.api.v1.model.provider.Location;
import com.ibm.liberty.starter.api.v1.model.provider.Provider;
import com.ibm.liberty.starter.api.v1.model.provider.Sample;
/*******************************************************************************
* Copyright (c) 2016 IBM Corp.
*
* 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.ibm.liberty.starter.service.template.api.v1.it;
/**
* Test the deployed service responds as expected
*
*/
public class TestApplication extends EndpointTest {
@Before
public void checkSetup() {
checkAvailability("/api/v1/provider/");
}
@Test
public void testProvider() throws Exception { | Provider provider = testEndpoint("/api/v1/provider/", Provider.class); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.