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
|
|---|---|---|---|---|---|---|
krtkush/MarsExplorer
|
app/src/main/java/io/github/krtkush/marsexplorer/Main/MainActivity.java
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/GeneralConstants.java
// public class GeneralConstants {
//
// // Rover names
// public static final String Curiosity = "Curiosity";
// public static final String Opportunity = "Opportunity";
// public static final String Spirit = "Spirit";
// }
|
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.krtkush.marsexplorer.GeneralConstants;
import io.github.krtkush.marsexplorer.R;
import timber.log.Timber;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
|
package io.github.krtkush.marsexplorer.Main;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.maxMarsTemperature) TextView maxTemperatureTextView;
@BindView(R.id.minMarsTemperature) TextView minTemperatureTextView;
@BindView(R.id.currentSol) TextView currentSolTextView;
@BindView(R.id.marsPressure) TextView atmosphericPressureTextView;
@BindView(R.id.goToCuriosityButtonBackground) ImageView goToCuriosityButtonBackground;
@BindView(R.id.goToOpportunityButtonBackground) ImageView goToOpportunityButtonBackground;
@BindView(R.id.goToSpiritButtonBackground) ImageView goToSpiritButtonBackground;
@BindView(R.id.headerImage) ImageView headerImage;
private MainActivityPresenterInteractor presenterInteractor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialise butterknife, timber and the presenter layer
ButterKnife.bind(MainActivity.this);
Timber.tag(MainActivity.this.getClass().getSimpleName());
presenterInteractor = new MainActivityPresenterLayer(this);
// Setup the toolbar
setSupportActionBar(toolbar);
presenterInteractor.setupToolbar(getSupportActionBar());
// Set the buttons background images
setImages(R.drawable.curiosity, goToCuriosityButtonBackground);
setImages(R.drawable.spirit, goToOpportunityButtonBackground);
setImages(R.drawable.opportunity, goToSpiritButtonBackground);
setImages(R.drawable.main_activity_header_mars_image, headerImage);
}
@Override
protected void onStart() {
super.onStart();
// Send request to get max SOL for each rover
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/GeneralConstants.java
// public class GeneralConstants {
//
// // Rover names
// public static final String Curiosity = "Curiosity";
// public static final String Opportunity = "Opportunity";
// public static final String Spirit = "Spirit";
// }
// Path: app/src/main/java/io/github/krtkush/marsexplorer/Main/MainActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.krtkush.marsexplorer.GeneralConstants;
import io.github.krtkush.marsexplorer.R;
import timber.log.Timber;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
package io.github.krtkush.marsexplorer.Main;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.maxMarsTemperature) TextView maxTemperatureTextView;
@BindView(R.id.minMarsTemperature) TextView minTemperatureTextView;
@BindView(R.id.currentSol) TextView currentSolTextView;
@BindView(R.id.marsPressure) TextView atmosphericPressureTextView;
@BindView(R.id.goToCuriosityButtonBackground) ImageView goToCuriosityButtonBackground;
@BindView(R.id.goToOpportunityButtonBackground) ImageView goToOpportunityButtonBackground;
@BindView(R.id.goToSpiritButtonBackground) ImageView goToSpiritButtonBackground;
@BindView(R.id.headerImage) ImageView headerImage;
private MainActivityPresenterInteractor presenterInteractor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialise butterknife, timber and the presenter layer
ButterKnife.bind(MainActivity.this);
Timber.tag(MainActivity.this.getClass().getSimpleName());
presenterInteractor = new MainActivityPresenterLayer(this);
// Setup the toolbar
setSupportActionBar(toolbar);
presenterInteractor.setupToolbar(getSupportActionBar());
// Set the buttons background images
setImages(R.drawable.curiosity, goToCuriosityButtonBackground);
setImages(R.drawable.spirit, goToOpportunityButtonBackground);
setImages(R.drawable.opportunity, goToSpiritButtonBackground);
setImages(R.drawable.main_activity_header_mars_image, headerImage);
}
@Override
protected void onStart() {
super.onStart();
// Send request to get max SOL for each rover
|
presenterInteractor.getMaxSol(GeneralConstants.Curiosity);
|
krtkush/MarsExplorer
|
app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/ResponseCacheInterceptor.java
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/RestClientConstants.java
// public class RestClientConstants {
//
// // Strings related to NASA's API
// private static final String nasaApiEndPoint = "https://api.nasa.gov/";
// private static final String nasaApiServiceName = "mars-photos/";
// private static final String nasaApiVersion = "api/v1/rovers/";
// public static final String nasaApiBaseUrl = nasaApiEndPoint + nasaApiServiceName
// + nasaApiVersion;
//
// // Strings related to Mars Weather's API
// private static final String marsWeatherEndPoint = "http://cab.inta-csic.es/";
// private static final String marsWeatherAddress = "rems/wp-content/plugins/marsweather-widget/";
// public static final String marsWeatherBaseUrl = marsWeatherEndPoint + marsWeatherAddress;
//
// // Custom headers
// public static final String responseCachingFlagHeader = "ApplyResponseCache";
// public static final String offlineCachingFlagHeader = "ApplyOfflineCache";
//
// // Cache directory name
// public static final String apiResponsesCache = "apiResponses";
// }
|
import java.io.IOException;
import io.github.krtkush.marsexplorer.RESTClients.RestClientConstants;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;
|
package io.github.krtkush.marsexplorer.RESTClients.Interceptors;
/**
* Created by kartikeykushwaha on 08/06/16.
*/
/**
* Interceptor to cache data and maintain it for six hour.
*
* If the same network request is sent within six hour, the response is retrieved from cache.
*/
public class ResponseCacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/RestClientConstants.java
// public class RestClientConstants {
//
// // Strings related to NASA's API
// private static final String nasaApiEndPoint = "https://api.nasa.gov/";
// private static final String nasaApiServiceName = "mars-photos/";
// private static final String nasaApiVersion = "api/v1/rovers/";
// public static final String nasaApiBaseUrl = nasaApiEndPoint + nasaApiServiceName
// + nasaApiVersion;
//
// // Strings related to Mars Weather's API
// private static final String marsWeatherEndPoint = "http://cab.inta-csic.es/";
// private static final String marsWeatherAddress = "rems/wp-content/plugins/marsweather-widget/";
// public static final String marsWeatherBaseUrl = marsWeatherEndPoint + marsWeatherAddress;
//
// // Custom headers
// public static final String responseCachingFlagHeader = "ApplyResponseCache";
// public static final String offlineCachingFlagHeader = "ApplyOfflineCache";
//
// // Cache directory name
// public static final String apiResponsesCache = "apiResponses";
// }
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/ResponseCacheInterceptor.java
import java.io.IOException;
import io.github.krtkush.marsexplorer.RESTClients.RestClientConstants;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;
package io.github.krtkush.marsexplorer.RESTClients.Interceptors;
/**
* Created by kartikeykushwaha on 08/06/16.
*/
/**
* Interceptor to cache data and maintain it for six hour.
*
* If the same network request is sent within six hour, the response is retrieved from cache.
*/
public class ResponseCacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
|
if(Boolean.valueOf(request.header(RestClientConstants.responseCachingFlagHeader))) {
|
krtkush/MarsExplorer
|
app/src/main/java/io/github/krtkush/marsexplorer/About/Credits/CreditsActivityPresenterLayer.java
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java
// public class UtilityMethods {
//
// /**
// * Method to detect network connection on the device
// * @return
// */
// public static boolean isNetworkAvailable() {
//
// ConnectivityManager connectivityManager =
// (ConnectivityManager) MarsExplorerApplication.getApplicationInstance()
// .getSystemService(MarsExplorerApplication.getApplicationInstance()
// .CONNECTIVITY_SERVICE);
//
// return connectivityManager.getActiveNetworkInfo() != null
// && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
// }
//
// /**
// * It's usually very important for websites to track where their traffic is coming from.
// * We make sure to let them know that we are sending them users by setting the referrer when
// * launching our Custom Tab.
// * @return The value of the Referrer Intent.
// */
// public static String customTabReferrerString() {
//
// int URI_ANDROID_APP_SCHEME;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 22)
// URI_ANDROID_APP_SCHEME = 1<<1;
// else
// URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME;
//
// return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance()
// .getPackageName();
// }
//
// /**
// * @return The Referrer intent key.
// */
// public static String customTabReferrerKey() {
//
// String EXTRA_REFERRER;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 17)
// EXTRA_REFERRER = "android.intent.extra.REFERRER";
// else
// EXTRA_REFERRER = Intent.EXTRA_REFERRER;
//
// return EXTRA_REFERRER;
// }
// }
|
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.widget.Toast;
import io.github.krtkush.marsexplorer.R;
import io.github.krtkush.marsexplorer.UtilityMethods;
|
package io.github.krtkush.marsexplorer.About.Credits;
/**
* Created by kartikeykushwaha on 22/10/16.
*/
public class CreditsActivityPresenterLayer implements CreditsActivityPresenterInteractor{
private CreditsActivity activity;
public CreditsActivityPresenterLayer(CreditsActivity activity) {
this.activity = activity;
}
@Override
public void checkInternetConnectivity() {
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java
// public class UtilityMethods {
//
// /**
// * Method to detect network connection on the device
// * @return
// */
// public static boolean isNetworkAvailable() {
//
// ConnectivityManager connectivityManager =
// (ConnectivityManager) MarsExplorerApplication.getApplicationInstance()
// .getSystemService(MarsExplorerApplication.getApplicationInstance()
// .CONNECTIVITY_SERVICE);
//
// return connectivityManager.getActiveNetworkInfo() != null
// && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
// }
//
// /**
// * It's usually very important for websites to track where their traffic is coming from.
// * We make sure to let them know that we are sending them users by setting the referrer when
// * launching our Custom Tab.
// * @return The value of the Referrer Intent.
// */
// public static String customTabReferrerString() {
//
// int URI_ANDROID_APP_SCHEME;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 22)
// URI_ANDROID_APP_SCHEME = 1<<1;
// else
// URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME;
//
// return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance()
// .getPackageName();
// }
//
// /**
// * @return The Referrer intent key.
// */
// public static String customTabReferrerKey() {
//
// String EXTRA_REFERRER;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 17)
// EXTRA_REFERRER = "android.intent.extra.REFERRER";
// else
// EXTRA_REFERRER = Intent.EXTRA_REFERRER;
//
// return EXTRA_REFERRER;
// }
// }
// Path: app/src/main/java/io/github/krtkush/marsexplorer/About/Credits/CreditsActivityPresenterLayer.java
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.widget.Toast;
import io.github.krtkush.marsexplorer.R;
import io.github.krtkush.marsexplorer.UtilityMethods;
package io.github.krtkush.marsexplorer.About.Credits;
/**
* Created by kartikeykushwaha on 22/10/16.
*/
public class CreditsActivityPresenterLayer implements CreditsActivityPresenterInteractor{
private CreditsActivity activity;
public CreditsActivityPresenterLayer(CreditsActivity activity) {
this.activity = activity;
}
@Override
public void checkInternetConnectivity() {
|
if(!UtilityMethods.isNetworkAvailable())
|
krtkush/MarsExplorer
|
app/src/main/java/io/github/krtkush/marsexplorer/About/Credits/CreditsRecyclerViewAdapter.java
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java
// public class UtilityMethods {
//
// /**
// * Method to detect network connection on the device
// * @return
// */
// public static boolean isNetworkAvailable() {
//
// ConnectivityManager connectivityManager =
// (ConnectivityManager) MarsExplorerApplication.getApplicationInstance()
// .getSystemService(MarsExplorerApplication.getApplicationInstance()
// .CONNECTIVITY_SERVICE);
//
// return connectivityManager.getActiveNetworkInfo() != null
// && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
// }
//
// /**
// * It's usually very important for websites to track where their traffic is coming from.
// * We make sure to let them know that we are sending them users by setting the referrer when
// * launching our Custom Tab.
// * @return The value of the Referrer Intent.
// */
// public static String customTabReferrerString() {
//
// int URI_ANDROID_APP_SCHEME;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 22)
// URI_ANDROID_APP_SCHEME = 1<<1;
// else
// URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME;
//
// return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance()
// .getPackageName();
// }
//
// /**
// * @return The Referrer intent key.
// */
// public static String customTabReferrerKey() {
//
// String EXTRA_REFERRER;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 17)
// EXTRA_REFERRER = "android.intent.extra.REFERRER";
// else
// EXTRA_REFERRER = Intent.EXTRA_REFERRER;
//
// return EXTRA_REFERRER;
// }
// }
|
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.customtabs.CustomTabsClient;
import android.support.customtabs.CustomTabsIntent;
import android.support.customtabs.CustomTabsServiceConnection;
import android.support.customtabs.CustomTabsSession;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.github.krtkush.marsexplorer.R;
import io.github.krtkush.marsexplorer.UtilityMethods;
|
* Method to prepare the CustomTabs.
*/
private void prepareCustomTabs() {
final String CUSTOM_TAB_PACKAGE_NAME = "com.android.chrome";
CustomTabsServiceConnection customTabsServiceConnection =
new CustomTabsServiceConnection() {
@Override
public void onCustomTabsServiceConnected(ComponentName name,
CustomTabsClient client) {
customTabsClient = client;
customTabsClient.warmup(0L);
customTabsSession = customTabsClient.newSession(null);
}
@Override
public void onServiceDisconnected(ComponentName name) {
customTabsClient = null;
}
};
isConnectedToCustomTabService = CustomTabsClient.bindCustomTabsService(activity,
CUSTOM_TAB_PACKAGE_NAME, customTabsServiceConnection);
customTabsIntent = new CustomTabsIntent.Builder(customTabsSession)
.setShowTitle(true)
.setStartAnimations(activity, R.anim.slide_up_enter, R.anim.stay)
.setExitAnimations(activity, R.anim.stay, R.anim.slide_down_exit)
.build();
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java
// public class UtilityMethods {
//
// /**
// * Method to detect network connection on the device
// * @return
// */
// public static boolean isNetworkAvailable() {
//
// ConnectivityManager connectivityManager =
// (ConnectivityManager) MarsExplorerApplication.getApplicationInstance()
// .getSystemService(MarsExplorerApplication.getApplicationInstance()
// .CONNECTIVITY_SERVICE);
//
// return connectivityManager.getActiveNetworkInfo() != null
// && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
// }
//
// /**
// * It's usually very important for websites to track where their traffic is coming from.
// * We make sure to let them know that we are sending them users by setting the referrer when
// * launching our Custom Tab.
// * @return The value of the Referrer Intent.
// */
// public static String customTabReferrerString() {
//
// int URI_ANDROID_APP_SCHEME;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 22)
// URI_ANDROID_APP_SCHEME = 1<<1;
// else
// URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME;
//
// return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance()
// .getPackageName();
// }
//
// /**
// * @return The Referrer intent key.
// */
// public static String customTabReferrerKey() {
//
// String EXTRA_REFERRER;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 17)
// EXTRA_REFERRER = "android.intent.extra.REFERRER";
// else
// EXTRA_REFERRER = Intent.EXTRA_REFERRER;
//
// return EXTRA_REFERRER;
// }
// }
// Path: app/src/main/java/io/github/krtkush/marsexplorer/About/Credits/CreditsRecyclerViewAdapter.java
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.customtabs.CustomTabsClient;
import android.support.customtabs.CustomTabsIntent;
import android.support.customtabs.CustomTabsServiceConnection;
import android.support.customtabs.CustomTabsSession;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.github.krtkush.marsexplorer.R;
import io.github.krtkush.marsexplorer.UtilityMethods;
* Method to prepare the CustomTabs.
*/
private void prepareCustomTabs() {
final String CUSTOM_TAB_PACKAGE_NAME = "com.android.chrome";
CustomTabsServiceConnection customTabsServiceConnection =
new CustomTabsServiceConnection() {
@Override
public void onCustomTabsServiceConnected(ComponentName name,
CustomTabsClient client) {
customTabsClient = client;
customTabsClient.warmup(0L);
customTabsSession = customTabsClient.newSession(null);
}
@Override
public void onServiceDisconnected(ComponentName name) {
customTabsClient = null;
}
};
isConnectedToCustomTabService = CustomTabsClient.bindCustomTabsService(activity,
CUSTOM_TAB_PACKAGE_NAME, customTabsServiceConnection);
customTabsIntent = new CustomTabsIntent.Builder(customTabsSession)
.setShowTitle(true)
.setStartAnimations(activity, R.anim.slide_up_enter, R.anim.stay)
.setExitAnimations(activity, R.anim.stay, R.anim.slide_down_exit)
.build();
|
customTabsIntent.intent.putExtra(UtilityMethods.customTabReferrerKey(),
|
krtkush/MarsExplorer
|
app/src/main/java/io/github/krtkush/marsexplorer/About/AboutActivityPresenterLayer.java
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/About/Credits/CreditsActivity.java
// public class CreditsActivity extends AppCompatActivity {
//
// @BindView(R.id.toolbar) Toolbar toolbar;
// @BindView(R.id.creditsRecyclerView) RecyclerView recyclerView;
//
// private CreditsActivityPresenterInteractor presenterInteractor;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_credits);
//
// // Initialise butterknife, timber and the presenter layer
// ButterKnife.bind(CreditsActivity.this);
// Timber.tag(CreditsActivity.this.getClass().getSimpleName());
// presenterInteractor = new CreditsActivityPresenterLayer(this);
//
// // Setup the toolbar
// setSupportActionBar(toolbar);
// getSupportActionBar().setTitle("Credits");
//
// // Show the credit list
// presenterInteractor.prepareRecyclerViewAndAddData(recyclerView);
// }
//
// @Override
// protected void attachBaseContext(Context newBase) {
// super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// presenterInteractor.checkInternetConnectivity();
// }
//
// /**
// * Method to make toast on this activity
// * @param toastMessage The message to be displayed
// * @param toastDuration Duration for the toast to be visible
// */
// protected void showToast(String toastMessage, int toastDuration) {
// Toast.makeText(this, toastMessage, toastDuration).show();
// }
// }
//
// Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java
// public class UtilityMethods {
//
// /**
// * Method to detect network connection on the device
// * @return
// */
// public static boolean isNetworkAvailable() {
//
// ConnectivityManager connectivityManager =
// (ConnectivityManager) MarsExplorerApplication.getApplicationInstance()
// .getSystemService(MarsExplorerApplication.getApplicationInstance()
// .CONNECTIVITY_SERVICE);
//
// return connectivityManager.getActiveNetworkInfo() != null
// && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
// }
//
// /**
// * It's usually very important for websites to track where their traffic is coming from.
// * We make sure to let them know that we are sending them users by setting the referrer when
// * launching our Custom Tab.
// * @return The value of the Referrer Intent.
// */
// public static String customTabReferrerString() {
//
// int URI_ANDROID_APP_SCHEME;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 22)
// URI_ANDROID_APP_SCHEME = 1<<1;
// else
// URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME;
//
// return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance()
// .getPackageName();
// }
//
// /**
// * @return The Referrer intent key.
// */
// public static String customTabReferrerKey() {
//
// String EXTRA_REFERRER;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 17)
// EXTRA_REFERRER = "android.intent.extra.REFERRER";
// else
// EXTRA_REFERRER = Intent.EXTRA_REFERRER;
//
// return EXTRA_REFERRER;
// }
// }
|
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.customtabs.CustomTabsClient;
import android.support.customtabs.CustomTabsIntent;
import android.support.customtabs.CustomTabsServiceConnection;
import android.support.customtabs.CustomTabsSession;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.view.MenuItem;
import android.widget.Toast;
import io.github.krtkush.marsexplorer.About.Credits.CreditsActivity;
import io.github.krtkush.marsexplorer.R;
import io.github.krtkush.marsexplorer.UtilityMethods;
|
package io.github.krtkush.marsexplorer.About;
/**
* Created by kartikeykushwaha on 21/10/16.
*/
public class AboutActivityPresenterLayer implements AboutActivityPresenterInteractor {
private AboutActivity activity;
// Variables for CustomTabs.
private CustomTabsIntent customTabsIntent;
private CustomTabsClient customTabsClient;
private CustomTabsSession customTabsSession;
private String DEVELOPER_PAGE = "https://krtkush.github.io";
private String GITHUB_PAGE = "https://github.com/krtkush/MarsExplorer";
// Keep track if the CustomTab is up and running. If not, open the links in the browser.
private boolean isConnectedToCustomTabService;
public AboutActivityPresenterLayer(AboutActivity activity) {
this.activity = activity;
prepareCustomTabs();
}
@Override
public void checkInternetConnectivity() {
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/About/Credits/CreditsActivity.java
// public class CreditsActivity extends AppCompatActivity {
//
// @BindView(R.id.toolbar) Toolbar toolbar;
// @BindView(R.id.creditsRecyclerView) RecyclerView recyclerView;
//
// private CreditsActivityPresenterInteractor presenterInteractor;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_credits);
//
// // Initialise butterknife, timber and the presenter layer
// ButterKnife.bind(CreditsActivity.this);
// Timber.tag(CreditsActivity.this.getClass().getSimpleName());
// presenterInteractor = new CreditsActivityPresenterLayer(this);
//
// // Setup the toolbar
// setSupportActionBar(toolbar);
// getSupportActionBar().setTitle("Credits");
//
// // Show the credit list
// presenterInteractor.prepareRecyclerViewAndAddData(recyclerView);
// }
//
// @Override
// protected void attachBaseContext(Context newBase) {
// super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// presenterInteractor.checkInternetConnectivity();
// }
//
// /**
// * Method to make toast on this activity
// * @param toastMessage The message to be displayed
// * @param toastDuration Duration for the toast to be visible
// */
// protected void showToast(String toastMessage, int toastDuration) {
// Toast.makeText(this, toastMessage, toastDuration).show();
// }
// }
//
// Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java
// public class UtilityMethods {
//
// /**
// * Method to detect network connection on the device
// * @return
// */
// public static boolean isNetworkAvailable() {
//
// ConnectivityManager connectivityManager =
// (ConnectivityManager) MarsExplorerApplication.getApplicationInstance()
// .getSystemService(MarsExplorerApplication.getApplicationInstance()
// .CONNECTIVITY_SERVICE);
//
// return connectivityManager.getActiveNetworkInfo() != null
// && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
// }
//
// /**
// * It's usually very important for websites to track where their traffic is coming from.
// * We make sure to let them know that we are sending them users by setting the referrer when
// * launching our Custom Tab.
// * @return The value of the Referrer Intent.
// */
// public static String customTabReferrerString() {
//
// int URI_ANDROID_APP_SCHEME;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 22)
// URI_ANDROID_APP_SCHEME = 1<<1;
// else
// URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME;
//
// return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance()
// .getPackageName();
// }
//
// /**
// * @return The Referrer intent key.
// */
// public static String customTabReferrerKey() {
//
// String EXTRA_REFERRER;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 17)
// EXTRA_REFERRER = "android.intent.extra.REFERRER";
// else
// EXTRA_REFERRER = Intent.EXTRA_REFERRER;
//
// return EXTRA_REFERRER;
// }
// }
// Path: app/src/main/java/io/github/krtkush/marsexplorer/About/AboutActivityPresenterLayer.java
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.customtabs.CustomTabsClient;
import android.support.customtabs.CustomTabsIntent;
import android.support.customtabs.CustomTabsServiceConnection;
import android.support.customtabs.CustomTabsSession;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.view.MenuItem;
import android.widget.Toast;
import io.github.krtkush.marsexplorer.About.Credits.CreditsActivity;
import io.github.krtkush.marsexplorer.R;
import io.github.krtkush.marsexplorer.UtilityMethods;
package io.github.krtkush.marsexplorer.About;
/**
* Created by kartikeykushwaha on 21/10/16.
*/
public class AboutActivityPresenterLayer implements AboutActivityPresenterInteractor {
private AboutActivity activity;
// Variables for CustomTabs.
private CustomTabsIntent customTabsIntent;
private CustomTabsClient customTabsClient;
private CustomTabsSession customTabsSession;
private String DEVELOPER_PAGE = "https://krtkush.github.io";
private String GITHUB_PAGE = "https://github.com/krtkush/MarsExplorer";
// Keep track if the CustomTab is up and running. If not, open the links in the browser.
private boolean isConnectedToCustomTabService;
public AboutActivityPresenterLayer(AboutActivity activity) {
this.activity = activity;
prepareCustomTabs();
}
@Override
public void checkInternetConnectivity() {
|
if(!UtilityMethods.isNetworkAvailable())
|
krtkush/MarsExplorer
|
app/src/main/java/io/github/krtkush/marsexplorer/About/AboutActivityPresenterLayer.java
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/About/Credits/CreditsActivity.java
// public class CreditsActivity extends AppCompatActivity {
//
// @BindView(R.id.toolbar) Toolbar toolbar;
// @BindView(R.id.creditsRecyclerView) RecyclerView recyclerView;
//
// private CreditsActivityPresenterInteractor presenterInteractor;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_credits);
//
// // Initialise butterknife, timber and the presenter layer
// ButterKnife.bind(CreditsActivity.this);
// Timber.tag(CreditsActivity.this.getClass().getSimpleName());
// presenterInteractor = new CreditsActivityPresenterLayer(this);
//
// // Setup the toolbar
// setSupportActionBar(toolbar);
// getSupportActionBar().setTitle("Credits");
//
// // Show the credit list
// presenterInteractor.prepareRecyclerViewAndAddData(recyclerView);
// }
//
// @Override
// protected void attachBaseContext(Context newBase) {
// super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// presenterInteractor.checkInternetConnectivity();
// }
//
// /**
// * Method to make toast on this activity
// * @param toastMessage The message to be displayed
// * @param toastDuration Duration for the toast to be visible
// */
// protected void showToast(String toastMessage, int toastDuration) {
// Toast.makeText(this, toastMessage, toastDuration).show();
// }
// }
//
// Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java
// public class UtilityMethods {
//
// /**
// * Method to detect network connection on the device
// * @return
// */
// public static boolean isNetworkAvailable() {
//
// ConnectivityManager connectivityManager =
// (ConnectivityManager) MarsExplorerApplication.getApplicationInstance()
// .getSystemService(MarsExplorerApplication.getApplicationInstance()
// .CONNECTIVITY_SERVICE);
//
// return connectivityManager.getActiveNetworkInfo() != null
// && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
// }
//
// /**
// * It's usually very important for websites to track where their traffic is coming from.
// * We make sure to let them know that we are sending them users by setting the referrer when
// * launching our Custom Tab.
// * @return The value of the Referrer Intent.
// */
// public static String customTabReferrerString() {
//
// int URI_ANDROID_APP_SCHEME;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 22)
// URI_ANDROID_APP_SCHEME = 1<<1;
// else
// URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME;
//
// return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance()
// .getPackageName();
// }
//
// /**
// * @return The Referrer intent key.
// */
// public static String customTabReferrerKey() {
//
// String EXTRA_REFERRER;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 17)
// EXTRA_REFERRER = "android.intent.extra.REFERRER";
// else
// EXTRA_REFERRER = Intent.EXTRA_REFERRER;
//
// return EXTRA_REFERRER;
// }
// }
|
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.customtabs.CustomTabsClient;
import android.support.customtabs.CustomTabsIntent;
import android.support.customtabs.CustomTabsServiceConnection;
import android.support.customtabs.CustomTabsSession;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.view.MenuItem;
import android.widget.Toast;
import io.github.krtkush.marsexplorer.About.Credits.CreditsActivity;
import io.github.krtkush.marsexplorer.R;
import io.github.krtkush.marsexplorer.UtilityMethods;
|
public void checkInternetConnectivity() {
if(!UtilityMethods.isNetworkAvailable())
activity.showToast(activity.getResources()
.getString(R.string.no_internet),
Toast.LENGTH_LONG);
}
@Override
public void populateVersionNumber() {
try {
PackageInfo packageInfo = activity.getPackageManager()
.getPackageInfo(activity.getPackageName(), 0);
activity.setVersionNumber(packageInfo.versionName);
} catch (PackageManager.NameNotFoundException ex) {
ex.printStackTrace();
}
}
@Override
public void handleOptionsSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(activity);
break;
}
}
@Override
public void goToCreditsSection() {
|
// Path: app/src/main/java/io/github/krtkush/marsexplorer/About/Credits/CreditsActivity.java
// public class CreditsActivity extends AppCompatActivity {
//
// @BindView(R.id.toolbar) Toolbar toolbar;
// @BindView(R.id.creditsRecyclerView) RecyclerView recyclerView;
//
// private CreditsActivityPresenterInteractor presenterInteractor;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_credits);
//
// // Initialise butterknife, timber and the presenter layer
// ButterKnife.bind(CreditsActivity.this);
// Timber.tag(CreditsActivity.this.getClass().getSimpleName());
// presenterInteractor = new CreditsActivityPresenterLayer(this);
//
// // Setup the toolbar
// setSupportActionBar(toolbar);
// getSupportActionBar().setTitle("Credits");
//
// // Show the credit list
// presenterInteractor.prepareRecyclerViewAndAddData(recyclerView);
// }
//
// @Override
// protected void attachBaseContext(Context newBase) {
// super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// presenterInteractor.checkInternetConnectivity();
// }
//
// /**
// * Method to make toast on this activity
// * @param toastMessage The message to be displayed
// * @param toastDuration Duration for the toast to be visible
// */
// protected void showToast(String toastMessage, int toastDuration) {
// Toast.makeText(this, toastMessage, toastDuration).show();
// }
// }
//
// Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java
// public class UtilityMethods {
//
// /**
// * Method to detect network connection on the device
// * @return
// */
// public static boolean isNetworkAvailable() {
//
// ConnectivityManager connectivityManager =
// (ConnectivityManager) MarsExplorerApplication.getApplicationInstance()
// .getSystemService(MarsExplorerApplication.getApplicationInstance()
// .CONNECTIVITY_SERVICE);
//
// return connectivityManager.getActiveNetworkInfo() != null
// && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
// }
//
// /**
// * It's usually very important for websites to track where their traffic is coming from.
// * We make sure to let them know that we are sending them users by setting the referrer when
// * launching our Custom Tab.
// * @return The value of the Referrer Intent.
// */
// public static String customTabReferrerString() {
//
// int URI_ANDROID_APP_SCHEME;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 22)
// URI_ANDROID_APP_SCHEME = 1<<1;
// else
// URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME;
//
// return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance()
// .getPackageName();
// }
//
// /**
// * @return The Referrer intent key.
// */
// public static String customTabReferrerKey() {
//
// String EXTRA_REFERRER;
//
// // Prepare for SDK version compatibility problems.
// if(Build.VERSION.SDK_INT < 17)
// EXTRA_REFERRER = "android.intent.extra.REFERRER";
// else
// EXTRA_REFERRER = Intent.EXTRA_REFERRER;
//
// return EXTRA_REFERRER;
// }
// }
// Path: app/src/main/java/io/github/krtkush/marsexplorer/About/AboutActivityPresenterLayer.java
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.customtabs.CustomTabsClient;
import android.support.customtabs.CustomTabsIntent;
import android.support.customtabs.CustomTabsServiceConnection;
import android.support.customtabs.CustomTabsSession;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.view.MenuItem;
import android.widget.Toast;
import io.github.krtkush.marsexplorer.About.Credits.CreditsActivity;
import io.github.krtkush.marsexplorer.R;
import io.github.krtkush.marsexplorer.UtilityMethods;
public void checkInternetConnectivity() {
if(!UtilityMethods.isNetworkAvailable())
activity.showToast(activity.getResources()
.getString(R.string.no_internet),
Toast.LENGTH_LONG);
}
@Override
public void populateVersionNumber() {
try {
PackageInfo packageInfo = activity.getPackageManager()
.getPackageInfo(activity.getPackageName(), 0);
activity.setVersionNumber(packageInfo.versionName);
} catch (PackageManager.NameNotFoundException ex) {
ex.printStackTrace();
}
}
@Override
public void handleOptionsSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(activity);
break;
}
}
@Override
public void goToCreditsSection() {
|
Intent goToCreditsList = new Intent(activity, CreditsActivity.class);
|
iminto/baicai
|
src/main/java/com/baicai/controller/common/BaseController.java
|
// Path: src/main/java/com/baicai/core/Constant.java
// public interface Constant {
// public static final String CHARSET = "UTF-8";
// public static final int CONCURRENT_CAPACITY_SIZE = 500;
// public static final int LOCKER_SLEEP_UNIT_TIME = 20;
//
// public static final int BUFFER_BYTE_SIZE = 8192;
// public static final String DOT=".";
// public static final String NULL = "null";
// public static final String SPACE = " ";
// public static final String QUOTE = "\"";
// public static int ioBufferSize = 16384;
//
// public static final String USER_SALT=PropertiesTool.get("system", "USER_SALT");
// }
|
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.HtmlUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baicai.core.Constant;
|
/**
* 客户端返回字符串
*
* @param response
* @param string
* @return
*/
protected String renderString(HttpServletResponse response, String string, String type) {
try {
response.reset();
response.setContentType(type);
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
return null;
} catch (IOException e) {
return null;
}
}
protected boolean isAjax(HttpServletRequest request){
boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
return isAjax;
}
@InitBinder
protected void initBinder(WebDataBinder binder) {
// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
|
// Path: src/main/java/com/baicai/core/Constant.java
// public interface Constant {
// public static final String CHARSET = "UTF-8";
// public static final int CONCURRENT_CAPACITY_SIZE = 500;
// public static final int LOCKER_SLEEP_UNIT_TIME = 20;
//
// public static final int BUFFER_BYTE_SIZE = 8192;
// public static final String DOT=".";
// public static final String NULL = "null";
// public static final String SPACE = " ";
// public static final String QUOTE = "\"";
// public static int ioBufferSize = 16384;
//
// public static final String USER_SALT=PropertiesTool.get("system", "USER_SALT");
// }
// Path: src/main/java/com/baicai/controller/common/BaseController.java
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.HtmlUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baicai.core.Constant;
/**
* 客户端返回字符串
*
* @param response
* @param string
* @return
*/
protected String renderString(HttpServletResponse response, String string, String type) {
try {
response.reset();
response.setContentType(type);
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
return null;
} catch (IOException e) {
return null;
}
}
protected boolean isAjax(HttpServletRequest request){
boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
return isAjax;
}
@InitBinder
protected void initBinder(WebDataBinder binder) {
// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
|
setValue(text == null ? null : HtmlUtils.htmlEscape(text,Constant.CHARSET));
|
iminto/baicai
|
src/main/java/com/baicai/service/system/MenuService.java
|
// Path: src/main/java/com/baicai/domain/system/menu/SysMenu.java
// public class SysMenu extends Model{
// private Integer id;//菜单ID
// private String menuname;//菜单名
// private Integer pid;//父节点
// private String url;//菜单连接
// private String iconurl;//icon图标地址或样式
// private String desc;//简单说明
// private Integer flag;//使用标记,1正常0禁用
// private String path;//路径表
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
// public String getMenuname() {
// return menuname;
// }
// public void setMenuname(String menuname) {
// this.menuname = menuname;
// }
// public Integer getPid() {
// return pid;
// }
// public void setPid(Integer pid) {
// this.pid = pid;
// }
// public String getUrl() {
// return url;
// }
// public void setUrl(String url) {
// this.url = url;
// }
// public String getIconurl() {
// return iconurl;
// }
// public void setIconurl(String iconurl) {
// this.iconurl = iconurl;
// }
// public String getDesc() {
// return desc;
// }
// public void setDesc(String desc) {
// this.desc = desc;
// }
// public Integer getFlag() {
// return flag;
// }
// public void setFlag(Integer flag) {
// this.flag = flag;
// }
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
//
//
// }
//
// Path: src/main/java/com/baicai/domain/system/menu/SysMenuTreeDomain.java
// public class SysMenuTreeDomain extends SysMenu {
// private List<SysMenuTreeDomain> child=new ArrayList<>();
//
// public List<SysMenuTreeDomain> getChild() {
// return child;
// }
//
// public void setChild(List<SysMenuTreeDomain> child) {
// this.child = child;
// }
//
// }
|
import java.util.ArrayList;
import java.util.List;
import com.baicai.domain.system.menu.SysMenu;
import com.baicai.domain.system.menu.SysMenuTreeDomain;
|
package com.baicai.service.system;
public class MenuService {
public List<SysMenu> getAllMenus() {
List<SysMenu> menus=new ArrayList<>();//待查取
return menus;
}
/**
* 递归获取树形菜单
*/
|
// Path: src/main/java/com/baicai/domain/system/menu/SysMenu.java
// public class SysMenu extends Model{
// private Integer id;//菜单ID
// private String menuname;//菜单名
// private Integer pid;//父节点
// private String url;//菜单连接
// private String iconurl;//icon图标地址或样式
// private String desc;//简单说明
// private Integer flag;//使用标记,1正常0禁用
// private String path;//路径表
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
// public String getMenuname() {
// return menuname;
// }
// public void setMenuname(String menuname) {
// this.menuname = menuname;
// }
// public Integer getPid() {
// return pid;
// }
// public void setPid(Integer pid) {
// this.pid = pid;
// }
// public String getUrl() {
// return url;
// }
// public void setUrl(String url) {
// this.url = url;
// }
// public String getIconurl() {
// return iconurl;
// }
// public void setIconurl(String iconurl) {
// this.iconurl = iconurl;
// }
// public String getDesc() {
// return desc;
// }
// public void setDesc(String desc) {
// this.desc = desc;
// }
// public Integer getFlag() {
// return flag;
// }
// public void setFlag(Integer flag) {
// this.flag = flag;
// }
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
//
//
// }
//
// Path: src/main/java/com/baicai/domain/system/menu/SysMenuTreeDomain.java
// public class SysMenuTreeDomain extends SysMenu {
// private List<SysMenuTreeDomain> child=new ArrayList<>();
//
// public List<SysMenuTreeDomain> getChild() {
// return child;
// }
//
// public void setChild(List<SysMenuTreeDomain> child) {
// this.child = child;
// }
//
// }
// Path: src/main/java/com/baicai/service/system/MenuService.java
import java.util.ArrayList;
import java.util.List;
import com.baicai.domain.system.menu.SysMenu;
import com.baicai.domain.system.menu.SysMenuTreeDomain;
package com.baicai.service.system;
public class MenuService {
public List<SysMenu> getAllMenus() {
List<SysMenu> menus=new ArrayList<>();//待查取
return menus;
}
/**
* 递归获取树形菜单
*/
|
public List<SysMenuTreeDomain> getAllMenusRecursion() {
|
iminto/baicai
|
src/main/java/com/baicai/core/Constant.java
|
// Path: src/main/java/com/baicai/corewith/util/PropertiesTool.java
// public class PropertiesTool {
// public static String get(String configFile, String key) {
// Properties properties = new Properties();
// try {
// properties.load(PropertiesTool.class.getClassLoader().getResourceAsStream(configFile+".properties"));
// String value = properties.getProperty(key);
// return value;
// } catch (IOException e) {
// e.printStackTrace();
// return "";
// }
// }
//
// public static void main(String[] args) throws IOException {
// System.out.println(get("system", "tableFix"));
// }
// }
|
import com.baicai.corewith.util.PropertiesTool;
|
package com.baicai.core;
public interface Constant {
public static final String CHARSET = "UTF-8";
public static final int CONCURRENT_CAPACITY_SIZE = 500;
public static final int LOCKER_SLEEP_UNIT_TIME = 20;
public static final int BUFFER_BYTE_SIZE = 8192;
public static final String DOT=".";
public static final String NULL = "null";
public static final String SPACE = " ";
public static final String QUOTE = "\"";
public static int ioBufferSize = 16384;
|
// Path: src/main/java/com/baicai/corewith/util/PropertiesTool.java
// public class PropertiesTool {
// public static String get(String configFile, String key) {
// Properties properties = new Properties();
// try {
// properties.load(PropertiesTool.class.getClassLoader().getResourceAsStream(configFile+".properties"));
// String value = properties.getProperty(key);
// return value;
// } catch (IOException e) {
// e.printStackTrace();
// return "";
// }
// }
//
// public static void main(String[] args) throws IOException {
// System.out.println(get("system", "tableFix"));
// }
// }
// Path: src/main/java/com/baicai/core/Constant.java
import com.baicai.corewith.util.PropertiesTool;
package com.baicai.core;
public interface Constant {
public static final String CHARSET = "UTF-8";
public static final int CONCURRENT_CAPACITY_SIZE = 500;
public static final int LOCKER_SLEEP_UNIT_TIME = 20;
public static final int BUFFER_BYTE_SIZE = 8192;
public static final String DOT=".";
public static final String NULL = "null";
public static final String SPACE = " ";
public static final String QUOTE = "\"";
public static int ioBufferSize = 16384;
|
public static final String USER_SALT=PropertiesTool.get("system", "USER_SALT");
|
iminto/baicai
|
src/main/java/org/springframework/web/util/WebLogbackConfigurer.java
|
// Path: src/main/java/org/springframework/web/util/LogbackConfigurer.java
// public class LogbackConfigurer {
//
// private LogbackConfigurer() {
// }
//
// /**
// * Initialize logback from the given file.
// *
// * @param location the location of the config file: either a "classpath:" location
// * (e.g. "classpath:logback.xml"), an absolute file URL
// * (e.g. "file:C:/logback.xml), or a plain absolute path in the file system
// * (e.g. "C:/logback.xml")
// * @throws java.io.FileNotFoundException if the location specifies an invalid file path
// * @throws ch.qos.logback.core.joran.spi.JoranException
// * Thrown
// */
// public static void initLogging(String location) throws FileNotFoundException, JoranException {
// String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
// URL url = ResourceUtils.getURL(resolvedLocation);
// LoggerContext loggerContext = (LoggerContext)StaticLoggerBinder.getSingleton().getLoggerFactory();
//
// // in the current version logback automatically configures at startup the context, so we have to reset it
// loggerContext.reset();
//
// // reinitialize the logger context. calling this method allows configuration through groovy or xml
// new ContextInitializer(loggerContext).configureByResource(url);
// }
//
// /**
// * Set the specified system property to the current working directory.
// * <p/>
// * This can be used e.g. for test environments, for applications that leverage
// * LogbackWebConfigurer's "webAppRootKey" support in a web environment.
// *
// * @param key system property key to use, as expected in Logback configuration
// * (for example: "demo.root", used as "${demo.root}/WEB-INF/demo.log")
// * @see ch.qos.logback.ext.spring.web.WebLogbackConfigurer WebLogbackConfigurer
// */
// public static void setWorkingDirSystemProperty(String key) {
// System.setProperty(key, new File("").getAbsolutePath());
// }
//
// /**
// * Shut down Logback.
// * <p/>
// * This isn't strictly necessary, but recommended for shutting down
// * logback in a scenario where the host VM stays alive (for example, when
// * shutting down an application in a J2EE environment).
// */
// public static void shutdownLogging() {
// ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
// LoggerContext loggerContext = selector.getLoggerContext();
// String loggerContextName = loggerContext.getName();
// LoggerContext context = selector.detachLoggerContext(loggerContextName);
// context.reset();
// }
// }
|
import ch.qos.logback.core.joran.spi.JoranException;
import org.springframework.web.util.LogbackConfigurer;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;
import org.springframework.web.util.WebUtils;
import javax.servlet.ServletContext;
import java.io.FileNotFoundException;
import java.lang.reflect.Method;
|
package org.springframework.web.util;
public class WebLogbackConfigurer {
public static final String CONFIG_LOCATION_PARAM = "logbackConfigLocation";
public static final String EXPOSE_WEB_APP_ROOT_PARAM = "logbackExposeWebAppRoot";
private WebLogbackConfigurer() {
}
public static void initLogging(ServletContext servletContext) {
// Expose the web app root system property.
if (exposeWebAppRoot(servletContext)) {
WebUtils.setWebAppRootSystemProperty(servletContext);
}
// Only perform custom Logback initialization in case of a config file.
String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
if (location != null) {
// Perform actual Logback initialization; else rely on Logback's default initialization.
try {
// Resolve system property placeholders before potentially resolving real path.
location = SystemPropertyUtils.resolvePlaceholders(location);
// Return a URL (e.g. "classpath:" or "file:") as-is;
// consider a plain file path as relative to the web application root directory.
if (!ResourceUtils.isUrl(location)) {
location = WebUtils.getRealPath(servletContext, location);
}
// Write log message to server log.
servletContext.log("Initializing Logback from [" + location + "]");
// Initialize
|
// Path: src/main/java/org/springframework/web/util/LogbackConfigurer.java
// public class LogbackConfigurer {
//
// private LogbackConfigurer() {
// }
//
// /**
// * Initialize logback from the given file.
// *
// * @param location the location of the config file: either a "classpath:" location
// * (e.g. "classpath:logback.xml"), an absolute file URL
// * (e.g. "file:C:/logback.xml), or a plain absolute path in the file system
// * (e.g. "C:/logback.xml")
// * @throws java.io.FileNotFoundException if the location specifies an invalid file path
// * @throws ch.qos.logback.core.joran.spi.JoranException
// * Thrown
// */
// public static void initLogging(String location) throws FileNotFoundException, JoranException {
// String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
// URL url = ResourceUtils.getURL(resolvedLocation);
// LoggerContext loggerContext = (LoggerContext)StaticLoggerBinder.getSingleton().getLoggerFactory();
//
// // in the current version logback automatically configures at startup the context, so we have to reset it
// loggerContext.reset();
//
// // reinitialize the logger context. calling this method allows configuration through groovy or xml
// new ContextInitializer(loggerContext).configureByResource(url);
// }
//
// /**
// * Set the specified system property to the current working directory.
// * <p/>
// * This can be used e.g. for test environments, for applications that leverage
// * LogbackWebConfigurer's "webAppRootKey" support in a web environment.
// *
// * @param key system property key to use, as expected in Logback configuration
// * (for example: "demo.root", used as "${demo.root}/WEB-INF/demo.log")
// * @see ch.qos.logback.ext.spring.web.WebLogbackConfigurer WebLogbackConfigurer
// */
// public static void setWorkingDirSystemProperty(String key) {
// System.setProperty(key, new File("").getAbsolutePath());
// }
//
// /**
// * Shut down Logback.
// * <p/>
// * This isn't strictly necessary, but recommended for shutting down
// * logback in a scenario where the host VM stays alive (for example, when
// * shutting down an application in a J2EE environment).
// */
// public static void shutdownLogging() {
// ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
// LoggerContext loggerContext = selector.getLoggerContext();
// String loggerContextName = loggerContext.getName();
// LoggerContext context = selector.detachLoggerContext(loggerContextName);
// context.reset();
// }
// }
// Path: src/main/java/org/springframework/web/util/WebLogbackConfigurer.java
import ch.qos.logback.core.joran.spi.JoranException;
import org.springframework.web.util.LogbackConfigurer;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;
import org.springframework.web.util.WebUtils;
import javax.servlet.ServletContext;
import java.io.FileNotFoundException;
import java.lang.reflect.Method;
package org.springframework.web.util;
public class WebLogbackConfigurer {
public static final String CONFIG_LOCATION_PARAM = "logbackConfigLocation";
public static final String EXPOSE_WEB_APP_ROOT_PARAM = "logbackExposeWebAppRoot";
private WebLogbackConfigurer() {
}
public static void initLogging(ServletContext servletContext) {
// Expose the web app root system property.
if (exposeWebAppRoot(servletContext)) {
WebUtils.setWebAppRootSystemProperty(servletContext);
}
// Only perform custom Logback initialization in case of a config file.
String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
if (location != null) {
// Perform actual Logback initialization; else rely on Logback's default initialization.
try {
// Resolve system property placeholders before potentially resolving real path.
location = SystemPropertyUtils.resolvePlaceholders(location);
// Return a URL (e.g. "classpath:" or "file:") as-is;
// consider a plain file path as relative to the web application root directory.
if (!ResourceUtils.isUrl(location)) {
location = WebUtils.getRealPath(servletContext, location);
}
// Write log message to server log.
servletContext.log("Initializing Logback from [" + location + "]");
// Initialize
|
LogbackConfigurer.initLogging(location);
|
iminto/baicai
|
src/main/java/com/baicai/core/database/TargetDataSource.java
|
// Path: src/main/java/com/baicai/core/database/DynamicDataSourceContextHolder.java
// public enum DS {DATA_SOURCE_1,DATA_SOURCE_2};
|
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.baicai.core.database.DynamicDataSourceContextHolder.DS;
|
package com.baicai.core.database;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
|
// Path: src/main/java/com/baicai/core/database/DynamicDataSourceContextHolder.java
// public enum DS {DATA_SOURCE_1,DATA_SOURCE_2};
// Path: src/main/java/com/baicai/core/database/TargetDataSource.java
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.baicai.core.database.DynamicDataSourceContextHolder.DS;
package com.baicai.core.database;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
|
public DS value() default DS.DATA_SOURCE_1;
|
iminto/baicai
|
src/main/java/com/baicai/controller/common/ExceptionControllerAdvice.java
|
// Path: src/main/java/com/baicai/core/BusinessException.java
// public class BusinessException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public BusinessException() {
// }
//
// public BusinessException(String message) {
// super(message);
// }
//
// public BusinessException(Throwable cause) {
// super(cause);
// }
//
// public BusinessException(String message, Throwable cause) {
// super(message, cause);
// }
//
// @Override
// public Throwable fillInStackTrace() {
// return null;
// }
//
// }
|
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.alibaba.fastjson.JSON;
import com.baicai.core.BusinessException;
|
package com.baicai.controller.common;
/**
* 全局异常处理,注意这里只能对contoller里抛出的异常进行拦截处理,其他的异常这里拦截不到
* @Description: TODO
* @author 猪肉有毒 waitfox@qq.com
* @date 2016年4月7日 下午11:03:18
* @version V1.0
* 我只为你回眸一笑,即使不够倾国倾城,我只为你付出此生,换来生再次相守
*/
@ControllerAdvice
public class ExceptionControllerAdvice {
private Logger log=LoggerFactory.getLogger(ExceptionControllerAdvice.class);
@ExceptionHandler
public String expAdvice(HttpServletRequest request, HttpServletResponse response, Exception ex){
ex.printStackTrace();
Map<String, Object> map = new HashMap<String, Object>();
if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
.getHeader("X-Requested-With") != null && request.getHeader(
"X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
// 如果不是ajax,返回页面
map.put("success", false);
|
// Path: src/main/java/com/baicai/core/BusinessException.java
// public class BusinessException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public BusinessException() {
// }
//
// public BusinessException(String message) {
// super(message);
// }
//
// public BusinessException(Throwable cause) {
// super(cause);
// }
//
// public BusinessException(String message, Throwable cause) {
// super(message, cause);
// }
//
// @Override
// public Throwable fillInStackTrace() {
// return null;
// }
//
// }
// Path: src/main/java/com/baicai/controller/common/ExceptionControllerAdvice.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.alibaba.fastjson.JSON;
import com.baicai.core.BusinessException;
package com.baicai.controller.common;
/**
* 全局异常处理,注意这里只能对contoller里抛出的异常进行拦截处理,其他的异常这里拦截不到
* @Description: TODO
* @author 猪肉有毒 waitfox@qq.com
* @date 2016年4月7日 下午11:03:18
* @version V1.0
* 我只为你回眸一笑,即使不够倾国倾城,我只为你付出此生,换来生再次相守
*/
@ControllerAdvice
public class ExceptionControllerAdvice {
private Logger log=LoggerFactory.getLogger(ExceptionControllerAdvice.class);
@ExceptionHandler
public String expAdvice(HttpServletRequest request, HttpServletResponse response, Exception ex){
ex.printStackTrace();
Map<String, Object> map = new HashMap<String, Object>();
if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
.getHeader("X-Requested-With") != null && request.getHeader(
"X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
// 如果不是ajax,返回页面
map.put("success", false);
|
if (ex instanceof BusinessException) {
|
iminto/baicai
|
src/main/java/com/baicai/core/database/DaoUtil.java
|
// Path: src/main/java/com/baicai/domain/system/Pagination.java
// public class Pagination {
// public Integer total=0;// 总条数
// public Integer pageSize = 10;// 每页条数
// public Integer page = 1;// 当前页数
// private Map pageParaMap;// 页面参数
// public Integer pageTotal=0;// 总页数
// public Integer offset;
//
// private List list;//容器
//
// public Pagination() {
// }
//
// public Pagination(int total) {
// this.total = total;
// }
//
// public Integer getTotal() {
// return total;
// }
//
// public void setTotal(Integer total) {
// this.total = total;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getPage() {
// return page>0?page:1;
// }
//
// public void setPage(Integer page) {
// if(page==null) page=1;
// this.page = page;
// }
//
// public Map getPageParaMap() {
// return pageParaMap;
// }
//
// public void setPageParaMap(Map pageParaMap) {
// this.pageParaMap = pageParaMap;
// }
//
// public Integer getPageTotal() {
// if(total==0) return 1;
// Integer totalPage = (total % pageSize == 0) ? (total / pageSize ): (total
// / pageSize + 1);
// return (totalPage==null || totalPage == 0) ? 1 : totalPage;
// }
//
// public void setPageTotal(Integer pageTotal) {
// this.pageTotal = pageTotal;
// }
//
// public static Integer pageInteger(String page) {
// Integer p = 1;
// if (page != null && !page.equals("")) {
// p = Integer.valueOf(page);
// }
// return p;
// }
//
// public List getList() {
// return list;
// }
//
// public void setList(List list) {
// this.list = list;
// }
//
// public Integer getOffset() {
// return (this.getPage()-1)*this.getPageSize();
// }
//
// /**
// * TODO:生成连接字符串,可用于GET方式的分页,待补充
// * @return
// */
// public String generateLink(){
// return "";
// }
//
// }
//
// Path: src/main/java/com/baicai/corewith/util/PropertiesTool.java
// public class PropertiesTool {
// public static String get(String configFile, String key) {
// Properties properties = new Properties();
// try {
// properties.load(PropertiesTool.class.getClassLoader().getResourceAsStream(configFile+".properties"));
// String value = properties.getProperty(key);
// return value;
// } catch (IOException e) {
// e.printStackTrace();
// return "";
// }
// }
//
// public static void main(String[] args) throws IOException {
// System.out.println(get("system", "tableFix"));
// }
// }
|
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baicai.corewith.annotation.Column;
import com.baicai.corewith.annotation.Key;
import com.baicai.corewith.annotation.Table;
import com.baicai.domain.system.Pagination;
import com.baicai.corewith.util.PropertiesTool;
|
package com.baicai.core.database;
/**
* DAO辅助类
*
* @author 白菜
*
*/
public class DaoUtil {
public static final String tableFix = PropertiesTool.get("system", "tableFix");
private static final Logger logger = LoggerFactory.getLogger(DaoUtil.class);
public static final String INSERT = "INSERT INTO ";
public static final String COMMA = ",";
public static final String COLON = ":";
public static final String BRACKET_LEFT = " ( ";
public static final String BRACKET_RIGHT = " ) ";
public static final String VALUES = " ) VALUES ( ";
public static final String APOSTROPHE = "`";
public static final String APOSTROPHECOMMA = "`,";
public static final String ASK = "?";
public static final String UPDATE = "UPDATE ";
public static final String WHERE = " WHERE ";
public static final String EQUAL = "=";
public static final String SET = " SET ";
public static String format(String sql) {
String result = sql.replace("{", tableFix);
result = result.replace("}", " ");
return result;
}
|
// Path: src/main/java/com/baicai/domain/system/Pagination.java
// public class Pagination {
// public Integer total=0;// 总条数
// public Integer pageSize = 10;// 每页条数
// public Integer page = 1;// 当前页数
// private Map pageParaMap;// 页面参数
// public Integer pageTotal=0;// 总页数
// public Integer offset;
//
// private List list;//容器
//
// public Pagination() {
// }
//
// public Pagination(int total) {
// this.total = total;
// }
//
// public Integer getTotal() {
// return total;
// }
//
// public void setTotal(Integer total) {
// this.total = total;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getPage() {
// return page>0?page:1;
// }
//
// public void setPage(Integer page) {
// if(page==null) page=1;
// this.page = page;
// }
//
// public Map getPageParaMap() {
// return pageParaMap;
// }
//
// public void setPageParaMap(Map pageParaMap) {
// this.pageParaMap = pageParaMap;
// }
//
// public Integer getPageTotal() {
// if(total==0) return 1;
// Integer totalPage = (total % pageSize == 0) ? (total / pageSize ): (total
// / pageSize + 1);
// return (totalPage==null || totalPage == 0) ? 1 : totalPage;
// }
//
// public void setPageTotal(Integer pageTotal) {
// this.pageTotal = pageTotal;
// }
//
// public static Integer pageInteger(String page) {
// Integer p = 1;
// if (page != null && !page.equals("")) {
// p = Integer.valueOf(page);
// }
// return p;
// }
//
// public List getList() {
// return list;
// }
//
// public void setList(List list) {
// this.list = list;
// }
//
// public Integer getOffset() {
// return (this.getPage()-1)*this.getPageSize();
// }
//
// /**
// * TODO:生成连接字符串,可用于GET方式的分页,待补充
// * @return
// */
// public String generateLink(){
// return "";
// }
//
// }
//
// Path: src/main/java/com/baicai/corewith/util/PropertiesTool.java
// public class PropertiesTool {
// public static String get(String configFile, String key) {
// Properties properties = new Properties();
// try {
// properties.load(PropertiesTool.class.getClassLoader().getResourceAsStream(configFile+".properties"));
// String value = properties.getProperty(key);
// return value;
// } catch (IOException e) {
// e.printStackTrace();
// return "";
// }
// }
//
// public static void main(String[] args) throws IOException {
// System.out.println(get("system", "tableFix"));
// }
// }
// Path: src/main/java/com/baicai/core/database/DaoUtil.java
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baicai.corewith.annotation.Column;
import com.baicai.corewith.annotation.Key;
import com.baicai.corewith.annotation.Table;
import com.baicai.domain.system.Pagination;
import com.baicai.corewith.util.PropertiesTool;
package com.baicai.core.database;
/**
* DAO辅助类
*
* @author 白菜
*
*/
public class DaoUtil {
public static final String tableFix = PropertiesTool.get("system", "tableFix");
private static final Logger logger = LoggerFactory.getLogger(DaoUtil.class);
public static final String INSERT = "INSERT INTO ";
public static final String COMMA = ",";
public static final String COLON = ":";
public static final String BRACKET_LEFT = " ( ";
public static final String BRACKET_RIGHT = " ) ";
public static final String VALUES = " ) VALUES ( ";
public static final String APOSTROPHE = "`";
public static final String APOSTROPHECOMMA = "`,";
public static final String ASK = "?";
public static final String UPDATE = "UPDATE ";
public static final String WHERE = " WHERE ";
public static final String EQUAL = "=";
public static final String SET = " SET ";
public static String format(String sql) {
String result = sql.replace("{", tableFix);
result = result.replace("}", " ");
return result;
}
|
public static String limit(Pagination page) {
|
marpies/vk-ane
|
android/src/com/marpies/ane/vk/VKExtension.java
|
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
// public class AIR {
//
// private static final String TAG = "VK";
// private static boolean mLogEnabled = false;
//
// private static VKExtensionContext mContext;
// private static VKAccessTokenTracker mTokenTracker;
//
// public static void log( String message ) {
// if( mLogEnabled ) {
// Log.i( TAG, message );
// }
// }
//
// public static void dispatchEvent( String eventName ) {
// dispatchEvent( eventName, "" );
// }
//
// public static void dispatchEvent( String eventName, String message ) {
// mContext.dispatchStatusEventAsync( eventName, message );
// }
//
// public static void startActivity( Class<?> activityClass, Bundle extras ) {
// Intent intent = new Intent( mContext.getActivity().getApplicationContext(), activityClass );
// ResolveInfo info = mContext.getActivity().getPackageManager().resolveActivity( intent, 0 );
// if( info == null ) {
// log( "Activity " + activityClass.getSimpleName() + " could not be started. Make sure you specified the activity in the android manifest." );
// return;
// }
// if( extras != null ) {
// intent.putExtras( extras );
// }
// mContext.getActivity().startActivity( intent );
// }
//
// public static void notifyTokenChange( VKAccessToken newToken ) {
// dispatchTokenChange( null, newToken );
// }
//
// public static void startAccessTokenTracker() {
// if( mTokenTracker == null ) {
// mTokenTracker = new VKAccessTokenTracker() {
// @Override
// public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// dispatchTokenChange( oldToken, newToken );
// }
// };
// mTokenTracker.startTracking();
// }
// }
//
// public static void stopAccessTokenTracker() {
// if( mTokenTracker != null ) {
// mTokenTracker.stopTracking();
// mTokenTracker = null;
// }
// }
//
// private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
// String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
// AIR.dispatchEvent( AIRVKEvent.VK_TOKEN_UPDATE, tokenJSON );
// }
//
// /**
// *
// *
// * Getters / Setters
// *
// *
// */
//
// public static VKExtensionContext getContext() {
// return mContext;
// }
// public static void setContext( VKExtensionContext context ) {
// mContext = context;
// }
//
// public static Boolean getLogEnabled() {
// return mLogEnabled;
// }
// public static void setLogEnabled( Boolean value ) {
// mLogEnabled = value;
// }
//
// }
|
import com.adobe.fre.FREContext;
import com.adobe.fre.FREExtension;
import com.marpies.ane.vk.utils.AIR;
|
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk;
public class VKExtension implements FREExtension {
@Override
public void initialize() { }
@Override
public FREContext createContext( String s ) {
|
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
// public class AIR {
//
// private static final String TAG = "VK";
// private static boolean mLogEnabled = false;
//
// private static VKExtensionContext mContext;
// private static VKAccessTokenTracker mTokenTracker;
//
// public static void log( String message ) {
// if( mLogEnabled ) {
// Log.i( TAG, message );
// }
// }
//
// public static void dispatchEvent( String eventName ) {
// dispatchEvent( eventName, "" );
// }
//
// public static void dispatchEvent( String eventName, String message ) {
// mContext.dispatchStatusEventAsync( eventName, message );
// }
//
// public static void startActivity( Class<?> activityClass, Bundle extras ) {
// Intent intent = new Intent( mContext.getActivity().getApplicationContext(), activityClass );
// ResolveInfo info = mContext.getActivity().getPackageManager().resolveActivity( intent, 0 );
// if( info == null ) {
// log( "Activity " + activityClass.getSimpleName() + " could not be started. Make sure you specified the activity in the android manifest." );
// return;
// }
// if( extras != null ) {
// intent.putExtras( extras );
// }
// mContext.getActivity().startActivity( intent );
// }
//
// public static void notifyTokenChange( VKAccessToken newToken ) {
// dispatchTokenChange( null, newToken );
// }
//
// public static void startAccessTokenTracker() {
// if( mTokenTracker == null ) {
// mTokenTracker = new VKAccessTokenTracker() {
// @Override
// public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// dispatchTokenChange( oldToken, newToken );
// }
// };
// mTokenTracker.startTracking();
// }
// }
//
// public static void stopAccessTokenTracker() {
// if( mTokenTracker != null ) {
// mTokenTracker.stopTracking();
// mTokenTracker = null;
// }
// }
//
// private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
// String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
// AIR.dispatchEvent( AIRVKEvent.VK_TOKEN_UPDATE, tokenJSON );
// }
//
// /**
// *
// *
// * Getters / Setters
// *
// *
// */
//
// public static VKExtensionContext getContext() {
// return mContext;
// }
// public static void setContext( VKExtensionContext context ) {
// mContext = context;
// }
//
// public static Boolean getLogEnabled() {
// return mLogEnabled;
// }
// public static void setLogEnabled( Boolean value ) {
// mLogEnabled = value;
// }
//
// }
// Path: android/src/com/marpies/ane/vk/VKExtension.java
import com.adobe.fre.FREContext;
import com.adobe.fre.FREExtension;
import com.marpies.ane.vk.utils.AIR;
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk;
public class VKExtension implements FREExtension {
@Override
public void initialize() { }
@Override
public FREContext createContext( String s ) {
|
AIR.setContext( new VKExtensionContext() );
|
marpies/vk-ane
|
android/src/com/marpies/ane/vk/VKExtensionContext.java
|
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
// public class AIR {
//
// private static final String TAG = "VK";
// private static boolean mLogEnabled = false;
//
// private static VKExtensionContext mContext;
// private static VKAccessTokenTracker mTokenTracker;
//
// public static void log( String message ) {
// if( mLogEnabled ) {
// Log.i( TAG, message );
// }
// }
//
// public static void dispatchEvent( String eventName ) {
// dispatchEvent( eventName, "" );
// }
//
// public static void dispatchEvent( String eventName, String message ) {
// mContext.dispatchStatusEventAsync( eventName, message );
// }
//
// public static void startActivity( Class<?> activityClass, Bundle extras ) {
// Intent intent = new Intent( mContext.getActivity().getApplicationContext(), activityClass );
// ResolveInfo info = mContext.getActivity().getPackageManager().resolveActivity( intent, 0 );
// if( info == null ) {
// log( "Activity " + activityClass.getSimpleName() + " could not be started. Make sure you specified the activity in the android manifest." );
// return;
// }
// if( extras != null ) {
// intent.putExtras( extras );
// }
// mContext.getActivity().startActivity( intent );
// }
//
// public static void notifyTokenChange( VKAccessToken newToken ) {
// dispatchTokenChange( null, newToken );
// }
//
// public static void startAccessTokenTracker() {
// if( mTokenTracker == null ) {
// mTokenTracker = new VKAccessTokenTracker() {
// @Override
// public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// dispatchTokenChange( oldToken, newToken );
// }
// };
// mTokenTracker.startTracking();
// }
// }
//
// public static void stopAccessTokenTracker() {
// if( mTokenTracker != null ) {
// mTokenTracker.stopTracking();
// mTokenTracker = null;
// }
// }
//
// private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
// String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
// AIR.dispatchEvent( AIRVKEvent.VK_TOKEN_UPDATE, tokenJSON );
// }
//
// /**
// *
// *
// * Getters / Setters
// *
// *
// */
//
// public static VKExtensionContext getContext() {
// return mContext;
// }
// public static void setContext( VKExtensionContext context ) {
// mContext = context;
// }
//
// public static Boolean getLogEnabled() {
// return mLogEnabled;
// }
// public static void setLogEnabled( Boolean value ) {
// mLogEnabled = value;
// }
//
// }
|
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.marpies.ane.vk.functions.*;
import com.marpies.ane.vk.utils.AIR;
import java.util.HashMap;
import java.util.Map;
|
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk;
public class VKExtensionContext extends FREContext {
@Override
public Map<String, FREFunction> getFunctions() {
Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
functions.put( "init", new InitFunction() );
functions.put( "auth", new AuthFunction() );
functions.put( "isLoggedIn", new IsLoggedInFunction() );
functions.put( "logout", new LogoutFunction() );
functions.put( "request", new RequestFunction() );
functions.put( "share", new ShareFunction() );
functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
functions.put( "sdkVersion", new GetSDKVersion() );
return functions;
}
@Override
public void dispose() {
|
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
// public class AIR {
//
// private static final String TAG = "VK";
// private static boolean mLogEnabled = false;
//
// private static VKExtensionContext mContext;
// private static VKAccessTokenTracker mTokenTracker;
//
// public static void log( String message ) {
// if( mLogEnabled ) {
// Log.i( TAG, message );
// }
// }
//
// public static void dispatchEvent( String eventName ) {
// dispatchEvent( eventName, "" );
// }
//
// public static void dispatchEvent( String eventName, String message ) {
// mContext.dispatchStatusEventAsync( eventName, message );
// }
//
// public static void startActivity( Class<?> activityClass, Bundle extras ) {
// Intent intent = new Intent( mContext.getActivity().getApplicationContext(), activityClass );
// ResolveInfo info = mContext.getActivity().getPackageManager().resolveActivity( intent, 0 );
// if( info == null ) {
// log( "Activity " + activityClass.getSimpleName() + " could not be started. Make sure you specified the activity in the android manifest." );
// return;
// }
// if( extras != null ) {
// intent.putExtras( extras );
// }
// mContext.getActivity().startActivity( intent );
// }
//
// public static void notifyTokenChange( VKAccessToken newToken ) {
// dispatchTokenChange( null, newToken );
// }
//
// public static void startAccessTokenTracker() {
// if( mTokenTracker == null ) {
// mTokenTracker = new VKAccessTokenTracker() {
// @Override
// public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// dispatchTokenChange( oldToken, newToken );
// }
// };
// mTokenTracker.startTracking();
// }
// }
//
// public static void stopAccessTokenTracker() {
// if( mTokenTracker != null ) {
// mTokenTracker.stopTracking();
// mTokenTracker = null;
// }
// }
//
// private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
// String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
// AIR.dispatchEvent( AIRVKEvent.VK_TOKEN_UPDATE, tokenJSON );
// }
//
// /**
// *
// *
// * Getters / Setters
// *
// *
// */
//
// public static VKExtensionContext getContext() {
// return mContext;
// }
// public static void setContext( VKExtensionContext context ) {
// mContext = context;
// }
//
// public static Boolean getLogEnabled() {
// return mLogEnabled;
// }
// public static void setLogEnabled( Boolean value ) {
// mLogEnabled = value;
// }
//
// }
// Path: android/src/com/marpies/ane/vk/VKExtensionContext.java
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.marpies.ane.vk.functions.*;
import com.marpies.ane.vk.utils.AIR;
import java.util.HashMap;
import java.util.Map;
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk;
public class VKExtensionContext extends FREContext {
@Override
public Map<String, FREFunction> getFunctions() {
Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
functions.put( "init", new InitFunction() );
functions.put( "auth", new AuthFunction() );
functions.put( "isLoggedIn", new IsLoggedInFunction() );
functions.put( "logout", new LogoutFunction() );
functions.put( "request", new RequestFunction() );
functions.put( "share", new ShareFunction() );
functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
functions.put( "sdkVersion", new GetSDKVersion() );
return functions;
}
@Override
public void dispose() {
|
AIR.stopAccessTokenTracker();
|
marpies/vk-ane
|
android/src/com/marpies/ane/vk/functions/BaseFunction.java
|
// Path: android/src/com/marpies/ane/vk/VKExtensionContext.java
// public class VKExtensionContext extends FREContext {
//
// @Override
// public Map<String, FREFunction> getFunctions() {
// Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
//
// functions.put( "init", new InitFunction() );
// functions.put( "auth", new AuthFunction() );
// functions.put( "isLoggedIn", new IsLoggedInFunction() );
// functions.put( "logout", new LogoutFunction() );
// functions.put( "request", new RequestFunction() );
// functions.put( "share", new ShareFunction() );
// functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
// functions.put( "sdkVersion", new GetSDKVersion() );
//
// return functions;
// }
//
// @Override
// public void dispose() {
// AIR.stopAccessTokenTracker();
// AIR.setContext( null );
// }
// }
//
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
// public class AIR {
//
// private static final String TAG = "VK";
// private static boolean mLogEnabled = false;
//
// private static VKExtensionContext mContext;
// private static VKAccessTokenTracker mTokenTracker;
//
// public static void log( String message ) {
// if( mLogEnabled ) {
// Log.i( TAG, message );
// }
// }
//
// public static void dispatchEvent( String eventName ) {
// dispatchEvent( eventName, "" );
// }
//
// public static void dispatchEvent( String eventName, String message ) {
// mContext.dispatchStatusEventAsync( eventName, message );
// }
//
// public static void startActivity( Class<?> activityClass, Bundle extras ) {
// Intent intent = new Intent( mContext.getActivity().getApplicationContext(), activityClass );
// ResolveInfo info = mContext.getActivity().getPackageManager().resolveActivity( intent, 0 );
// if( info == null ) {
// log( "Activity " + activityClass.getSimpleName() + " could not be started. Make sure you specified the activity in the android manifest." );
// return;
// }
// if( extras != null ) {
// intent.putExtras( extras );
// }
// mContext.getActivity().startActivity( intent );
// }
//
// public static void notifyTokenChange( VKAccessToken newToken ) {
// dispatchTokenChange( null, newToken );
// }
//
// public static void startAccessTokenTracker() {
// if( mTokenTracker == null ) {
// mTokenTracker = new VKAccessTokenTracker() {
// @Override
// public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// dispatchTokenChange( oldToken, newToken );
// }
// };
// mTokenTracker.startTracking();
// }
// }
//
// public static void stopAccessTokenTracker() {
// if( mTokenTracker != null ) {
// mTokenTracker.stopTracking();
// mTokenTracker = null;
// }
// }
//
// private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
// String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
// AIR.dispatchEvent( AIRVKEvent.VK_TOKEN_UPDATE, tokenJSON );
// }
//
// /**
// *
// *
// * Getters / Setters
// *
// *
// */
//
// public static VKExtensionContext getContext() {
// return mContext;
// }
// public static void setContext( VKExtensionContext context ) {
// mContext = context;
// }
//
// public static Boolean getLogEnabled() {
// return mLogEnabled;
// }
// public static void setLogEnabled( Boolean value ) {
// mLogEnabled = value;
// }
//
// }
|
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.marpies.ane.vk.VKExtensionContext;
import com.marpies.ane.vk.utils.AIR;
|
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk.functions;
public class BaseFunction implements FREFunction {
protected int mCallbackID;
@Override
public FREObject call( FREContext context, FREObject[] args ) {
|
// Path: android/src/com/marpies/ane/vk/VKExtensionContext.java
// public class VKExtensionContext extends FREContext {
//
// @Override
// public Map<String, FREFunction> getFunctions() {
// Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
//
// functions.put( "init", new InitFunction() );
// functions.put( "auth", new AuthFunction() );
// functions.put( "isLoggedIn", new IsLoggedInFunction() );
// functions.put( "logout", new LogoutFunction() );
// functions.put( "request", new RequestFunction() );
// functions.put( "share", new ShareFunction() );
// functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
// functions.put( "sdkVersion", new GetSDKVersion() );
//
// return functions;
// }
//
// @Override
// public void dispose() {
// AIR.stopAccessTokenTracker();
// AIR.setContext( null );
// }
// }
//
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
// public class AIR {
//
// private static final String TAG = "VK";
// private static boolean mLogEnabled = false;
//
// private static VKExtensionContext mContext;
// private static VKAccessTokenTracker mTokenTracker;
//
// public static void log( String message ) {
// if( mLogEnabled ) {
// Log.i( TAG, message );
// }
// }
//
// public static void dispatchEvent( String eventName ) {
// dispatchEvent( eventName, "" );
// }
//
// public static void dispatchEvent( String eventName, String message ) {
// mContext.dispatchStatusEventAsync( eventName, message );
// }
//
// public static void startActivity( Class<?> activityClass, Bundle extras ) {
// Intent intent = new Intent( mContext.getActivity().getApplicationContext(), activityClass );
// ResolveInfo info = mContext.getActivity().getPackageManager().resolveActivity( intent, 0 );
// if( info == null ) {
// log( "Activity " + activityClass.getSimpleName() + " could not be started. Make sure you specified the activity in the android manifest." );
// return;
// }
// if( extras != null ) {
// intent.putExtras( extras );
// }
// mContext.getActivity().startActivity( intent );
// }
//
// public static void notifyTokenChange( VKAccessToken newToken ) {
// dispatchTokenChange( null, newToken );
// }
//
// public static void startAccessTokenTracker() {
// if( mTokenTracker == null ) {
// mTokenTracker = new VKAccessTokenTracker() {
// @Override
// public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// dispatchTokenChange( oldToken, newToken );
// }
// };
// mTokenTracker.startTracking();
// }
// }
//
// public static void stopAccessTokenTracker() {
// if( mTokenTracker != null ) {
// mTokenTracker.stopTracking();
// mTokenTracker = null;
// }
// }
//
// private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
// String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
// AIR.dispatchEvent( AIRVKEvent.VK_TOKEN_UPDATE, tokenJSON );
// }
//
// /**
// *
// *
// * Getters / Setters
// *
// *
// */
//
// public static VKExtensionContext getContext() {
// return mContext;
// }
// public static void setContext( VKExtensionContext context ) {
// mContext = context;
// }
//
// public static Boolean getLogEnabled() {
// return mLogEnabled;
// }
// public static void setLogEnabled( Boolean value ) {
// mLogEnabled = value;
// }
//
// }
// Path: android/src/com/marpies/ane/vk/functions/BaseFunction.java
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.marpies.ane.vk.VKExtensionContext;
import com.marpies.ane.vk.utils.AIR;
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk.functions;
public class BaseFunction implements FREFunction {
protected int mCallbackID;
@Override
public FREObject call( FREContext context, FREObject[] args ) {
|
AIR.setContext( (VKExtensionContext) context );
|
marpies/vk-ane
|
android/src/com/marpies/ane/vk/functions/BaseFunction.java
|
// Path: android/src/com/marpies/ane/vk/VKExtensionContext.java
// public class VKExtensionContext extends FREContext {
//
// @Override
// public Map<String, FREFunction> getFunctions() {
// Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
//
// functions.put( "init", new InitFunction() );
// functions.put( "auth", new AuthFunction() );
// functions.put( "isLoggedIn", new IsLoggedInFunction() );
// functions.put( "logout", new LogoutFunction() );
// functions.put( "request", new RequestFunction() );
// functions.put( "share", new ShareFunction() );
// functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
// functions.put( "sdkVersion", new GetSDKVersion() );
//
// return functions;
// }
//
// @Override
// public void dispose() {
// AIR.stopAccessTokenTracker();
// AIR.setContext( null );
// }
// }
//
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
// public class AIR {
//
// private static final String TAG = "VK";
// private static boolean mLogEnabled = false;
//
// private static VKExtensionContext mContext;
// private static VKAccessTokenTracker mTokenTracker;
//
// public static void log( String message ) {
// if( mLogEnabled ) {
// Log.i( TAG, message );
// }
// }
//
// public static void dispatchEvent( String eventName ) {
// dispatchEvent( eventName, "" );
// }
//
// public static void dispatchEvent( String eventName, String message ) {
// mContext.dispatchStatusEventAsync( eventName, message );
// }
//
// public static void startActivity( Class<?> activityClass, Bundle extras ) {
// Intent intent = new Intent( mContext.getActivity().getApplicationContext(), activityClass );
// ResolveInfo info = mContext.getActivity().getPackageManager().resolveActivity( intent, 0 );
// if( info == null ) {
// log( "Activity " + activityClass.getSimpleName() + " could not be started. Make sure you specified the activity in the android manifest." );
// return;
// }
// if( extras != null ) {
// intent.putExtras( extras );
// }
// mContext.getActivity().startActivity( intent );
// }
//
// public static void notifyTokenChange( VKAccessToken newToken ) {
// dispatchTokenChange( null, newToken );
// }
//
// public static void startAccessTokenTracker() {
// if( mTokenTracker == null ) {
// mTokenTracker = new VKAccessTokenTracker() {
// @Override
// public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// dispatchTokenChange( oldToken, newToken );
// }
// };
// mTokenTracker.startTracking();
// }
// }
//
// public static void stopAccessTokenTracker() {
// if( mTokenTracker != null ) {
// mTokenTracker.stopTracking();
// mTokenTracker = null;
// }
// }
//
// private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
// String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
// AIR.dispatchEvent( AIRVKEvent.VK_TOKEN_UPDATE, tokenJSON );
// }
//
// /**
// *
// *
// * Getters / Setters
// *
// *
// */
//
// public static VKExtensionContext getContext() {
// return mContext;
// }
// public static void setContext( VKExtensionContext context ) {
// mContext = context;
// }
//
// public static Boolean getLogEnabled() {
// return mLogEnabled;
// }
// public static void setLogEnabled( Boolean value ) {
// mLogEnabled = value;
// }
//
// }
|
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.marpies.ane.vk.VKExtensionContext;
import com.marpies.ane.vk.utils.AIR;
|
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk.functions;
public class BaseFunction implements FREFunction {
protected int mCallbackID;
@Override
public FREObject call( FREContext context, FREObject[] args ) {
|
// Path: android/src/com/marpies/ane/vk/VKExtensionContext.java
// public class VKExtensionContext extends FREContext {
//
// @Override
// public Map<String, FREFunction> getFunctions() {
// Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
//
// functions.put( "init", new InitFunction() );
// functions.put( "auth", new AuthFunction() );
// functions.put( "isLoggedIn", new IsLoggedInFunction() );
// functions.put( "logout", new LogoutFunction() );
// functions.put( "request", new RequestFunction() );
// functions.put( "share", new ShareFunction() );
// functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
// functions.put( "sdkVersion", new GetSDKVersion() );
//
// return functions;
// }
//
// @Override
// public void dispose() {
// AIR.stopAccessTokenTracker();
// AIR.setContext( null );
// }
// }
//
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
// public class AIR {
//
// private static final String TAG = "VK";
// private static boolean mLogEnabled = false;
//
// private static VKExtensionContext mContext;
// private static VKAccessTokenTracker mTokenTracker;
//
// public static void log( String message ) {
// if( mLogEnabled ) {
// Log.i( TAG, message );
// }
// }
//
// public static void dispatchEvent( String eventName ) {
// dispatchEvent( eventName, "" );
// }
//
// public static void dispatchEvent( String eventName, String message ) {
// mContext.dispatchStatusEventAsync( eventName, message );
// }
//
// public static void startActivity( Class<?> activityClass, Bundle extras ) {
// Intent intent = new Intent( mContext.getActivity().getApplicationContext(), activityClass );
// ResolveInfo info = mContext.getActivity().getPackageManager().resolveActivity( intent, 0 );
// if( info == null ) {
// log( "Activity " + activityClass.getSimpleName() + " could not be started. Make sure you specified the activity in the android manifest." );
// return;
// }
// if( extras != null ) {
// intent.putExtras( extras );
// }
// mContext.getActivity().startActivity( intent );
// }
//
// public static void notifyTokenChange( VKAccessToken newToken ) {
// dispatchTokenChange( null, newToken );
// }
//
// public static void startAccessTokenTracker() {
// if( mTokenTracker == null ) {
// mTokenTracker = new VKAccessTokenTracker() {
// @Override
// public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// dispatchTokenChange( oldToken, newToken );
// }
// };
// mTokenTracker.startTracking();
// }
// }
//
// public static void stopAccessTokenTracker() {
// if( mTokenTracker != null ) {
// mTokenTracker.stopTracking();
// mTokenTracker = null;
// }
// }
//
// private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
// AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
// String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
// AIR.dispatchEvent( AIRVKEvent.VK_TOKEN_UPDATE, tokenJSON );
// }
//
// /**
// *
// *
// * Getters / Setters
// *
// *
// */
//
// public static VKExtensionContext getContext() {
// return mContext;
// }
// public static void setContext( VKExtensionContext context ) {
// mContext = context;
// }
//
// public static Boolean getLogEnabled() {
// return mLogEnabled;
// }
// public static void setLogEnabled( Boolean value ) {
// mLogEnabled = value;
// }
//
// }
// Path: android/src/com/marpies/ane/vk/functions/BaseFunction.java
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.marpies.ane.vk.VKExtensionContext;
import com.marpies.ane.vk.utils.AIR;
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk.functions;
public class BaseFunction implements FREFunction {
protected int mCallbackID;
@Override
public FREObject call( FREContext context, FREObject[] args ) {
|
AIR.setContext( (VKExtensionContext) context );
|
marpies/vk-ane
|
android/src/com/marpies/ane/vk/utils/AIR.java
|
// Path: android/src/com/marpies/ane/vk/VKExtensionContext.java
// public class VKExtensionContext extends FREContext {
//
// @Override
// public Map<String, FREFunction> getFunctions() {
// Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
//
// functions.put( "init", new InitFunction() );
// functions.put( "auth", new AuthFunction() );
// functions.put( "isLoggedIn", new IsLoggedInFunction() );
// functions.put( "logout", new LogoutFunction() );
// functions.put( "request", new RequestFunction() );
// functions.put( "share", new ShareFunction() );
// functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
// functions.put( "sdkVersion", new GetSDKVersion() );
//
// return functions;
// }
//
// @Override
// public void dispose() {
// AIR.stopAccessTokenTracker();
// AIR.setContext( null );
// }
// }
//
// Path: android/src/com/marpies/ane/vk/data/AIRVKEvent.java
// public class AIRVKEvent {
//
// public static final String VK_AUTH_ERROR = "vkAuthError";
// public static final String VK_AUTH_SUCCESS = "vkAuthSuccess";
// public static final String VK_TOKEN_UPDATE = "vkTokenUpdate";
// public static final String VK_REQUEST_SUCCESS = "vkRequestSuccess";
// public static final String VK_REQUEST_ERROR = "vkRequestError";
// public static final String VK_SHARE_COMPLETE = "vkShareComplete";
// public static final String VK_SHARE_CANCEL = "vkShareCancel";
// public static final String VK_SHARE_ERROR = "vkShareError";
//
// }
|
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import com.marpies.ane.vk.VKExtensionContext;
import com.marpies.ane.vk.data.AIRVKEvent;
import com.vk.sdk.VKAccessToken;
import com.vk.sdk.VKAccessTokenTracker;
|
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk.utils;
public class AIR {
private static final String TAG = "VK";
private static boolean mLogEnabled = false;
|
// Path: android/src/com/marpies/ane/vk/VKExtensionContext.java
// public class VKExtensionContext extends FREContext {
//
// @Override
// public Map<String, FREFunction> getFunctions() {
// Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
//
// functions.put( "init", new InitFunction() );
// functions.put( "auth", new AuthFunction() );
// functions.put( "isLoggedIn", new IsLoggedInFunction() );
// functions.put( "logout", new LogoutFunction() );
// functions.put( "request", new RequestFunction() );
// functions.put( "share", new ShareFunction() );
// functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
// functions.put( "sdkVersion", new GetSDKVersion() );
//
// return functions;
// }
//
// @Override
// public void dispose() {
// AIR.stopAccessTokenTracker();
// AIR.setContext( null );
// }
// }
//
// Path: android/src/com/marpies/ane/vk/data/AIRVKEvent.java
// public class AIRVKEvent {
//
// public static final String VK_AUTH_ERROR = "vkAuthError";
// public static final String VK_AUTH_SUCCESS = "vkAuthSuccess";
// public static final String VK_TOKEN_UPDATE = "vkTokenUpdate";
// public static final String VK_REQUEST_SUCCESS = "vkRequestSuccess";
// public static final String VK_REQUEST_ERROR = "vkRequestError";
// public static final String VK_SHARE_COMPLETE = "vkShareComplete";
// public static final String VK_SHARE_CANCEL = "vkShareCancel";
// public static final String VK_SHARE_ERROR = "vkShareError";
//
// }
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import com.marpies.ane.vk.VKExtensionContext;
import com.marpies.ane.vk.data.AIRVKEvent;
import com.vk.sdk.VKAccessToken;
import com.vk.sdk.VKAccessTokenTracker;
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marpies.ane.vk.utils;
public class AIR {
private static final String TAG = "VK";
private static boolean mLogEnabled = false;
|
private static VKExtensionContext mContext;
|
marpies/vk-ane
|
android/src/com/marpies/ane/vk/utils/AIR.java
|
// Path: android/src/com/marpies/ane/vk/VKExtensionContext.java
// public class VKExtensionContext extends FREContext {
//
// @Override
// public Map<String, FREFunction> getFunctions() {
// Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
//
// functions.put( "init", new InitFunction() );
// functions.put( "auth", new AuthFunction() );
// functions.put( "isLoggedIn", new IsLoggedInFunction() );
// functions.put( "logout", new LogoutFunction() );
// functions.put( "request", new RequestFunction() );
// functions.put( "share", new ShareFunction() );
// functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
// functions.put( "sdkVersion", new GetSDKVersion() );
//
// return functions;
// }
//
// @Override
// public void dispose() {
// AIR.stopAccessTokenTracker();
// AIR.setContext( null );
// }
// }
//
// Path: android/src/com/marpies/ane/vk/data/AIRVKEvent.java
// public class AIRVKEvent {
//
// public static final String VK_AUTH_ERROR = "vkAuthError";
// public static final String VK_AUTH_SUCCESS = "vkAuthSuccess";
// public static final String VK_TOKEN_UPDATE = "vkTokenUpdate";
// public static final String VK_REQUEST_SUCCESS = "vkRequestSuccess";
// public static final String VK_REQUEST_ERROR = "vkRequestError";
// public static final String VK_SHARE_COMPLETE = "vkShareComplete";
// public static final String VK_SHARE_CANCEL = "vkShareCancel";
// public static final String VK_SHARE_ERROR = "vkShareError";
//
// }
|
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import com.marpies.ane.vk.VKExtensionContext;
import com.marpies.ane.vk.data.AIRVKEvent;
import com.vk.sdk.VKAccessToken;
import com.vk.sdk.VKAccessTokenTracker;
|
}
mContext.getActivity().startActivity( intent );
}
public static void notifyTokenChange( VKAccessToken newToken ) {
dispatchTokenChange( null, newToken );
}
public static void startAccessTokenTracker() {
if( mTokenTracker == null ) {
mTokenTracker = new VKAccessTokenTracker() {
@Override
public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
dispatchTokenChange( oldToken, newToken );
}
};
mTokenTracker.startTracking();
}
}
public static void stopAccessTokenTracker() {
if( mTokenTracker != null ) {
mTokenTracker.stopTracking();
mTokenTracker = null;
}
}
private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
|
// Path: android/src/com/marpies/ane/vk/VKExtensionContext.java
// public class VKExtensionContext extends FREContext {
//
// @Override
// public Map<String, FREFunction> getFunctions() {
// Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
//
// functions.put( "init", new InitFunction() );
// functions.put( "auth", new AuthFunction() );
// functions.put( "isLoggedIn", new IsLoggedInFunction() );
// functions.put( "logout", new LogoutFunction() );
// functions.put( "request", new RequestFunction() );
// functions.put( "share", new ShareFunction() );
// functions.put( "applicationOpenURL", new ApplicationOpenURLFunction() );
// functions.put( "sdkVersion", new GetSDKVersion() );
//
// return functions;
// }
//
// @Override
// public void dispose() {
// AIR.stopAccessTokenTracker();
// AIR.setContext( null );
// }
// }
//
// Path: android/src/com/marpies/ane/vk/data/AIRVKEvent.java
// public class AIRVKEvent {
//
// public static final String VK_AUTH_ERROR = "vkAuthError";
// public static final String VK_AUTH_SUCCESS = "vkAuthSuccess";
// public static final String VK_TOKEN_UPDATE = "vkTokenUpdate";
// public static final String VK_REQUEST_SUCCESS = "vkRequestSuccess";
// public static final String VK_REQUEST_ERROR = "vkRequestError";
// public static final String VK_SHARE_COMPLETE = "vkShareComplete";
// public static final String VK_SHARE_CANCEL = "vkShareCancel";
// public static final String VK_SHARE_ERROR = "vkShareError";
//
// }
// Path: android/src/com/marpies/ane/vk/utils/AIR.java
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import com.marpies.ane.vk.VKExtensionContext;
import com.marpies.ane.vk.data.AIRVKEvent;
import com.vk.sdk.VKAccessToken;
import com.vk.sdk.VKAccessTokenTracker;
}
mContext.getActivity().startActivity( intent );
}
public static void notifyTokenChange( VKAccessToken newToken ) {
dispatchTokenChange( null, newToken );
}
public static void startAccessTokenTracker() {
if( mTokenTracker == null ) {
mTokenTracker = new VKAccessTokenTracker() {
@Override
public void onVKAccessTokenChanged( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
dispatchTokenChange( oldToken, newToken );
}
};
mTokenTracker.startTracking();
}
}
public static void stopAccessTokenTracker() {
if( mTokenTracker != null ) {
mTokenTracker.stopTracking();
mTokenTracker = null;
}
}
private static void dispatchTokenChange( @Nullable VKAccessToken oldToken, @Nullable VKAccessToken newToken ) {
AIR.log( "VKAccessTokenTracker::onVKAccessTokenChanged() new: " + newToken + " old: " + oldToken );
String tokenJSON = (newToken == null) ? "{}" : VKAccessTokenUtils.toJSON( newToken );
|
AIR.dispatchEvent( AIRVKEvent.VK_TOKEN_UPDATE, tokenJSON );
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/test/TestHelper.java
|
// Path: fixb/src/main/java/org/fixb/impl/FormatConstants.java
// public static final char SOH = 0x01;
|
import static org.fixb.impl.FormatConstants.SOH;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.test;
public class TestHelper {
public static String fix(String... fields) {
StringBuilder result = new StringBuilder();
for (String field : fields) {
|
// Path: fixb/src/main/java/org/fixb/impl/FormatConstants.java
// public static final char SOH = 0x01;
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
import static org.fixb.impl.FormatConstants.SOH;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.test;
public class TestHelper {
public static String fix(String... fields) {
StringBuilder result = new StringBuilder();
for (String field : fields) {
|
if (result.length() > 0) result.append(SOH);
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/meta/MutableFixMetaDictionaryTest.java
|
// Path: fixb/src/test/java/org/fixb/meta/MutableFixMetaDictionaryTest.java
// @FixBlock
// public static class Part {
// @FixField(tag = 123)
// final int value;
//
// public Part(@FixField(tag = 123) int value) {
// this.value = value;
// }
// }
|
import org.fixb.annotations.FixBlock;
import org.fixb.annotations.FixField;
import org.fixb.annotations.FixGroup;
import org.fixb.annotations.FixMessage;
import org.junit.Test;
import java.util.List;
import static junit.framework.Assert.*;
import static org.fixb.meta.MutableFixMetaDictionaryTest.Sample.Part;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.meta;
public class MutableFixMetaDictionaryTest {
private MutableFixMetaDictionary fixMetaDictionary = new MutableFixMetaDictionary();
@Test
public void testGetMetaForUnregisteredClassRegistersMessageType() {
// When
final FixMessageMeta<Sample> meta = fixMetaDictionary.getMetaForClass(Sample.class);
// Then
assertSame(meta, fixMetaDictionary.getMetaForMessageType("TEST"));
}
@Test
public void testGetMetaForRegisteredClassReturnsPreloadedMeta() {
// Given
final FixMessageMeta<Sample> meta = fixMetaDictionary.getMetaForClass(Sample.class);
// When / Then
assertSame(meta, fixMetaDictionary.getMetaForClass(Sample.class));
}
@Test(expected = IllegalStateException.class)
public void testGetMetaForFixBlockClassThrowsException() {
// Given
fixMetaDictionary.getMetaForClass(Sample.class);
|
// Path: fixb/src/test/java/org/fixb/meta/MutableFixMetaDictionaryTest.java
// @FixBlock
// public static class Part {
// @FixField(tag = 123)
// final int value;
//
// public Part(@FixField(tag = 123) int value) {
// this.value = value;
// }
// }
// Path: fixb/src/test/java/org/fixb/meta/MutableFixMetaDictionaryTest.java
import org.fixb.annotations.FixBlock;
import org.fixb.annotations.FixField;
import org.fixb.annotations.FixGroup;
import org.fixb.annotations.FixMessage;
import org.junit.Test;
import java.util.List;
import static junit.framework.Assert.*;
import static org.fixb.meta.MutableFixMetaDictionaryTest.Sample.Part;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.meta;
public class MutableFixMetaDictionaryTest {
private MutableFixMetaDictionary fixMetaDictionary = new MutableFixMetaDictionary();
@Test
public void testGetMetaForUnregisteredClassRegistersMessageType() {
// When
final FixMessageMeta<Sample> meta = fixMetaDictionary.getMetaForClass(Sample.class);
// Then
assertSame(meta, fixMetaDictionary.getMetaForMessageType("TEST"));
}
@Test
public void testGetMetaForRegisteredClassReturnsPreloadedMeta() {
// Given
final FixMessageMeta<Sample> meta = fixMetaDictionary.getMetaForClass(Sample.class);
// When / Then
assertSame(meta, fixMetaDictionary.getMetaForClass(Sample.class));
}
@Test(expected = IllegalStateException.class)
public void testGetMetaForFixBlockClassThrowsException() {
// Given
fixMetaDictionary.getMetaForClass(Sample.class);
|
assertTrue(fixMetaDictionary.containsMeta(Part.class));
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
|
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import org.fixb.FixException;
import org.fixb.annotations.FixValue;
import java.lang.reflect.Field;
|
package org.fixb.meta;
/**
* A metadata for a FIX enum binding.
*
* @author vladyslav.yatsenko
* @see FixEnumDictionary
*/
public class FixEnumMeta<T extends Enum<T>> {
private final Class<T> enumClass;
private final BiMap<String, T> enumFixValues;
public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
if (!type.isEnum()) {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import org.fixb.FixException;
import org.fixb.annotations.FixValue;
import java.lang.reflect.Field;
package org.fixb.meta;
/**
* A metadata for a FIX enum binding.
*
* @author vladyslav.yatsenko
* @see FixEnumDictionary
*/
public class FixEnumMeta<T extends Enum<T>> {
private final Class<T> enumClass;
private final BiMap<String, T> enumFixValues;
public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
if (!type.isEnum()) {
|
throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/test/data/TestModels.java
|
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
|
import org.fixb.annotations.FixBlock;
import org.fixb.annotations.FixField;
import org.fixb.annotations.FixMessage;
import static org.fixb.test.data.TestModels.QuoteFixFields.*;
|
this.value = value;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Component component = (Component) o;
if (value != null ? !value.equals(component.value) : component.value != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}
//////////////////////
// Quote
|
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
import org.fixb.annotations.FixBlock;
import org.fixb.annotations.FixField;
import org.fixb.annotations.FixMessage;
import static org.fixb.test.data.TestModels.QuoteFixFields.*;
this.value = value;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Component component = (Component) o;
if (value != null ? !value.equals(component.value) : component.value != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}
//////////////////////
// Quote
|
public static final class QuoteFixFields {
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/impl/NativeFixFieldExtractor.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixFieldExtractor.java
// public interface FixFieldExtractor<M> {
//
// /**
// * Reads a tag of the FIX field identified by the given tag. If optional is true then in case of not found field
// * null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage a FIX message object
// * @param type a type to return
// * @param tag a FIX field tag to read the tag from
// * @param optional determines whether a not found field should generate an exception
// * @param <T> the type of the result
// * @throws FixException
// */
// <T> T getFieldValue(M fixMessage, Class<T> type, int tag, boolean optional);
//
// /**
// * Reads all repeating groups from the given FIX message identified by the given tag. If optional is true then in
// * case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param elementType type of the resulting collection elements (has the same meaning as the type parameter in
// * getFieldValue)
// * @param elementTag the group delimiter tag (or the tag of a single element)
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// Class<T> elementType,
// int elementTag,
// boolean optional);
//
// /**
// * Reads all repeating block groups from the given FIX message identified by the given tag. If optional is true
// * then in case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param componentMeta the FIX mapping metadata for a single repeating group
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// FixBlockMeta<T> componentMeta,
// boolean optional);
// }
|
import org.fixb.FixException;
import org.fixb.FixFieldExtractor;
import org.fixb.meta.*;
import org.joda.time.*;
import java.math.BigDecimal;
import java.util.*;
|
if (f instanceof FixConstantFieldMeta) continue;
final Object fieldValue;
if (f.isGroup()) {
final FixGroupMeta groupMeta = (FixGroupMeta) f;
fieldValue = groupMeta.isSimple() ?
getGroups(cursor,
(Class<Collection<Object>>) groupMeta.getType(),
groupMeta.getTag(),
(Class<Object>) groupMeta.getComponentType(),
groupMeta.getComponentTag(),
groupMeta.isOptional()) :
getGroups(cursor,
(Class<Collection<Object>>) groupMeta.getType(),
groupMeta.getTag(),
(FixBlockMeta<Object>) groupMeta.getComponentMeta(),
groupMeta.isOptional());
} else {
fieldValue = extractFieldValue(cursor, f.getTag(), f.getType(), f.isOptional());
}
values.put(f, fieldValue);
}
return componentMeta.createModel(values);
}
private <T, C extends Collection<T>> C getGroups(FieldCursor cursor, Class<C> type, int groupTag, FixBlockMeta<T> componentMeta, boolean optional) {
if (!cursor.nextField(groupTag)) {
if (optional) {
return CollectionFactory.createCollection(type);
} else {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixFieldExtractor.java
// public interface FixFieldExtractor<M> {
//
// /**
// * Reads a tag of the FIX field identified by the given tag. If optional is true then in case of not found field
// * null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage a FIX message object
// * @param type a type to return
// * @param tag a FIX field tag to read the tag from
// * @param optional determines whether a not found field should generate an exception
// * @param <T> the type of the result
// * @throws FixException
// */
// <T> T getFieldValue(M fixMessage, Class<T> type, int tag, boolean optional);
//
// /**
// * Reads all repeating groups from the given FIX message identified by the given tag. If optional is true then in
// * case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param elementType type of the resulting collection elements (has the same meaning as the type parameter in
// * getFieldValue)
// * @param elementTag the group delimiter tag (or the tag of a single element)
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// Class<T> elementType,
// int elementTag,
// boolean optional);
//
// /**
// * Reads all repeating block groups from the given FIX message identified by the given tag. If optional is true
// * then in case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param componentMeta the FIX mapping metadata for a single repeating group
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// FixBlockMeta<T> componentMeta,
// boolean optional);
// }
// Path: fixb/src/main/java/org/fixb/impl/NativeFixFieldExtractor.java
import org.fixb.FixException;
import org.fixb.FixFieldExtractor;
import org.fixb.meta.*;
import org.joda.time.*;
import java.math.BigDecimal;
import java.util.*;
if (f instanceof FixConstantFieldMeta) continue;
final Object fieldValue;
if (f.isGroup()) {
final FixGroupMeta groupMeta = (FixGroupMeta) f;
fieldValue = groupMeta.isSimple() ?
getGroups(cursor,
(Class<Collection<Object>>) groupMeta.getType(),
groupMeta.getTag(),
(Class<Object>) groupMeta.getComponentType(),
groupMeta.getComponentTag(),
groupMeta.isOptional()) :
getGroups(cursor,
(Class<Collection<Object>>) groupMeta.getType(),
groupMeta.getTag(),
(FixBlockMeta<Object>) groupMeta.getComponentMeta(),
groupMeta.isOptional());
} else {
fieldValue = extractFieldValue(cursor, f.getTag(), f.getType(), f.isOptional());
}
values.put(f, fieldValue);
}
return componentMeta.createModel(values);
}
private <T, C extends Collection<T>> C getGroups(FieldCursor cursor, Class<C> type, int groupTag, FixBlockMeta<T> componentMeta, boolean optional) {
if (!cursor.nextField(groupTag)) {
if (optional) {
return CollectionFactory.createCollection(type);
} else {
|
throw FixException.fieldNotFound(groupTag, cursor.fixMessage);
|
YTEQ/fixb
|
fixb-perf-test/src/main/java/org/fixb/test/perf/TestModels.java
|
// Path: fixb-perf-test/src/main/java/org/fixb/test/perf/TestModels.java
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
|
import org.fixb.annotations.FixBlock;
import org.fixb.annotations.FixField;
import org.fixb.annotations.FixGroup;
import org.fixb.annotations.FixMessage;
import java.util.List;
import static org.fixb.test.perf.TestModels.QuoteFixFields.*;
|
this.value = value;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Component component = (Component) o;
if (value != null ? !value.equals(component.value) : component.value != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}
//////////////////////
// Quote
|
// Path: fixb-perf-test/src/main/java/org/fixb/test/perf/TestModels.java
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
// Path: fixb-perf-test/src/main/java/org/fixb/test/perf/TestModels.java
import org.fixb.annotations.FixBlock;
import org.fixb.annotations.FixField;
import org.fixb.annotations.FixGroup;
import org.fixb.annotations.FixMessage;
import java.util.List;
import static org.fixb.test.perf.TestModels.QuoteFixFields.*;
this.value = value;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Component component = (Component) o;
if (value != null ? !value.equals(component.value) : component.value != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}
//////////////////////
// Quote
|
public static final class QuoteFixFields {
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/meta/FixMetaScanner.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixFieldMeta fixFieldMeta(int tag, Object value, boolean header) {
// return new FixConstantFieldMeta(tag, header, value);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixGroupMeta fixGroupMeta(int groupTag,
// boolean header,
// boolean optional,
// int componentTag,
// Class<?> componentType,
// Field... path) {
// return new FixGroupMeta(groupTag, header, optional, componentTag, componentType, path);
// }
|
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.fixb.FixException;
import org.fixb.annotations.*;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import static org.fixb.meta.FixFieldMeta.fixFieldMeta;
import static org.fixb.meta.FixFieldMeta.fixGroupMeta;
|
/**
* Scans the given class for FIX mapping annotations.
*
* @param model the domain class to scan
* @param <T> the domain type to scan
* @return a FixBlockMeta for the given type.
* @throws FixException if the given class is not properly annotated.
*/
public static <T> FixBlockMeta<T> scanClass(Class<T> model) {
return scanClassAndAddToDictionary(model, new MutableFixMetaDictionary());
}
static <T> FixBlockMeta<T> scanClassAndAddToDictionary(Class<T> model, MutableFixMetaDictionary fixMetaDictionary) {
if (fixMetaDictionary.containsMeta(model)) {
return fixMetaDictionary.getComponentMeta(model);
}
final FixBlockMeta<T> result = scanClass(model, fixMetaDictionary);
fixMetaDictionary.addMeta(result);
return result;
}
static <T> FixBlockMeta<T> scanClass(Class<T> model, MutableFixMetaDictionary dictionary) {
if (dictionary.containsMeta(model)) {
return dictionary.getComponentMeta(model);
}
final FixBlockMeta<T> result;
if (model.getConstructors().length == 0) {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixFieldMeta fixFieldMeta(int tag, Object value, boolean header) {
// return new FixConstantFieldMeta(tag, header, value);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixGroupMeta fixGroupMeta(int groupTag,
// boolean header,
// boolean optional,
// int componentTag,
// Class<?> componentType,
// Field... path) {
// return new FixGroupMeta(groupTag, header, optional, componentTag, componentType, path);
// }
// Path: fixb/src/main/java/org/fixb/meta/FixMetaScanner.java
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.fixb.FixException;
import org.fixb.annotations.*;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import static org.fixb.meta.FixFieldMeta.fixFieldMeta;
import static org.fixb.meta.FixFieldMeta.fixGroupMeta;
/**
* Scans the given class for FIX mapping annotations.
*
* @param model the domain class to scan
* @param <T> the domain type to scan
* @return a FixBlockMeta for the given type.
* @throws FixException if the given class is not properly annotated.
*/
public static <T> FixBlockMeta<T> scanClass(Class<T> model) {
return scanClassAndAddToDictionary(model, new MutableFixMetaDictionary());
}
static <T> FixBlockMeta<T> scanClassAndAddToDictionary(Class<T> model, MutableFixMetaDictionary fixMetaDictionary) {
if (fixMetaDictionary.containsMeta(model)) {
return fixMetaDictionary.getComponentMeta(model);
}
final FixBlockMeta<T> result = scanClass(model, fixMetaDictionary);
fixMetaDictionary.addMeta(result);
return result;
}
static <T> FixBlockMeta<T> scanClass(Class<T> model, MutableFixMetaDictionary dictionary) {
if (dictionary.containsMeta(model)) {
return dictionary.getComponentMeta(model);
}
final FixBlockMeta<T> result;
if (model.getConstructors().length == 0) {
|
throw new FixException("Class [" + model.getName() + "] does not provide a public constructor.");
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/meta/FixMetaScanner.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixFieldMeta fixFieldMeta(int tag, Object value, boolean header) {
// return new FixConstantFieldMeta(tag, header, value);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixGroupMeta fixGroupMeta(int groupTag,
// boolean header,
// boolean optional,
// int componentTag,
// Class<?> componentType,
// Field... path) {
// return new FixGroupMeta(groupTag, header, optional, componentTag, componentType, path);
// }
|
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.fixb.FixException;
import org.fixb.annotations.*;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import static org.fixb.meta.FixFieldMeta.fixFieldMeta;
import static org.fixb.meta.FixFieldMeta.fixGroupMeta;
|
sortedClasses.addAll(allClasses);
return sortedClasses;
}
private static int numberOfFixParameters(Constructor<?> constructor) {
int fixAnnotationCount = 0;
for (Annotation[] annotations : constructor.getParameterAnnotations()) {
if (hasFixParamAnnotation(annotations)) {
fixAnnotationCount++;
}
}
return fixAnnotationCount;
}
private static boolean hasFixParamAnnotation(Annotation[] annotations) {
if (annotations.length == 0) {
return false;
}
final Set<Class<? extends Annotation>> fixAnnotationType = new HashSet<>(asList(FixBlock.class, FixField.class, FixGroup.class));
for (Annotation annotation : annotations) {
if (fixAnnotationType.contains(annotation.annotationType())) {
return true;
}
}
return false;
}
private static List<FixFieldMeta> processConstantFields(FixMessage messageAnnotation) {
final List<FixFieldMeta> headerFields = new ArrayList<>();
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixFieldMeta fixFieldMeta(int tag, Object value, boolean header) {
// return new FixConstantFieldMeta(tag, header, value);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixGroupMeta fixGroupMeta(int groupTag,
// boolean header,
// boolean optional,
// int componentTag,
// Class<?> componentType,
// Field... path) {
// return new FixGroupMeta(groupTag, header, optional, componentTag, componentType, path);
// }
// Path: fixb/src/main/java/org/fixb/meta/FixMetaScanner.java
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.fixb.FixException;
import org.fixb.annotations.*;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import static org.fixb.meta.FixFieldMeta.fixFieldMeta;
import static org.fixb.meta.FixFieldMeta.fixGroupMeta;
sortedClasses.addAll(allClasses);
return sortedClasses;
}
private static int numberOfFixParameters(Constructor<?> constructor) {
int fixAnnotationCount = 0;
for (Annotation[] annotations : constructor.getParameterAnnotations()) {
if (hasFixParamAnnotation(annotations)) {
fixAnnotationCount++;
}
}
return fixAnnotationCount;
}
private static boolean hasFixParamAnnotation(Annotation[] annotations) {
if (annotations.length == 0) {
return false;
}
final Set<Class<? extends Annotation>> fixAnnotationType = new HashSet<>(asList(FixBlock.class, FixField.class, FixGroup.class));
for (Annotation annotation : annotations) {
if (fixAnnotationType.contains(annotation.annotationType())) {
return true;
}
}
return false;
}
private static List<FixFieldMeta> processConstantFields(FixMessage messageAnnotation) {
final List<FixFieldMeta> headerFields = new ArrayList<>();
|
headerFields.add(fixFieldMeta(MSG_TYPE_TAG, messageAnnotation.type(), true));
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/meta/FixMetaScanner.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixFieldMeta fixFieldMeta(int tag, Object value, boolean header) {
// return new FixConstantFieldMeta(tag, header, value);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixGroupMeta fixGroupMeta(int groupTag,
// boolean header,
// boolean optional,
// int componentTag,
// Class<?> componentType,
// Field... path) {
// return new FixGroupMeta(groupTag, header, optional, componentTag, componentType, path);
// }
|
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.fixb.FixException;
import org.fixb.annotations.*;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import static org.fixb.meta.FixFieldMeta.fixFieldMeta;
import static org.fixb.meta.FixFieldMeta.fixGroupMeta;
|
sortedClasses.addAll(allClasses);
return sortedClasses;
}
private static int numberOfFixParameters(Constructor<?> constructor) {
int fixAnnotationCount = 0;
for (Annotation[] annotations : constructor.getParameterAnnotations()) {
if (hasFixParamAnnotation(annotations)) {
fixAnnotationCount++;
}
}
return fixAnnotationCount;
}
private static boolean hasFixParamAnnotation(Annotation[] annotations) {
if (annotations.length == 0) {
return false;
}
final Set<Class<? extends Annotation>> fixAnnotationType = new HashSet<>(asList(FixBlock.class, FixField.class, FixGroup.class));
for (Annotation annotation : annotations) {
if (fixAnnotationType.contains(annotation.annotationType())) {
return true;
}
}
return false;
}
private static List<FixFieldMeta> processConstantFields(FixMessage messageAnnotation) {
final List<FixFieldMeta> headerFields = new ArrayList<>();
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixFieldMeta fixFieldMeta(int tag, Object value, boolean header) {
// return new FixConstantFieldMeta(tag, header, value);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixGroupMeta fixGroupMeta(int groupTag,
// boolean header,
// boolean optional,
// int componentTag,
// Class<?> componentType,
// Field... path) {
// return new FixGroupMeta(groupTag, header, optional, componentTag, componentType, path);
// }
// Path: fixb/src/main/java/org/fixb/meta/FixMetaScanner.java
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.fixb.FixException;
import org.fixb.annotations.*;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import static org.fixb.meta.FixFieldMeta.fixFieldMeta;
import static org.fixb.meta.FixFieldMeta.fixGroupMeta;
sortedClasses.addAll(allClasses);
return sortedClasses;
}
private static int numberOfFixParameters(Constructor<?> constructor) {
int fixAnnotationCount = 0;
for (Annotation[] annotations : constructor.getParameterAnnotations()) {
if (hasFixParamAnnotation(annotations)) {
fixAnnotationCount++;
}
}
return fixAnnotationCount;
}
private static boolean hasFixParamAnnotation(Annotation[] annotations) {
if (annotations.length == 0) {
return false;
}
final Set<Class<? extends Annotation>> fixAnnotationType = new HashSet<>(asList(FixBlock.class, FixField.class, FixGroup.class));
for (Annotation annotation : annotations) {
if (fixAnnotationType.contains(annotation.annotationType())) {
return true;
}
}
return false;
}
private static List<FixFieldMeta> processConstantFields(FixMessage messageAnnotation) {
final List<FixFieldMeta> headerFields = new ArrayList<>();
|
headerFields.add(fixFieldMeta(MSG_TYPE_TAG, messageAnnotation.type(), true));
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/meta/FixMetaScanner.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixFieldMeta fixFieldMeta(int tag, Object value, boolean header) {
// return new FixConstantFieldMeta(tag, header, value);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixGroupMeta fixGroupMeta(int groupTag,
// boolean header,
// boolean optional,
// int componentTag,
// Class<?> componentType,
// Field... path) {
// return new FixGroupMeta(groupTag, header, optional, componentTag, componentType, path);
// }
|
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.fixb.FixException;
import org.fixb.annotations.*;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import static org.fixb.meta.FixFieldMeta.fixFieldMeta;
import static org.fixb.meta.FixFieldMeta.fixGroupMeta;
|
final Field[] path = newPath(parentPath, f);
for (Annotation annotation : f.getDeclaredAnnotations()) {
if (FixField.class == annotation.annotationType()) {
FixField fixField = (FixField) annotation;
int tag = fixField.tag();
if (fixFields.containsKey(tag)) {
throw new FixException("There are more than one fields mapped with FIX tag [" + tag + "].");
}
fixFields.put(tag, fixFieldMeta(tag, fixField.header(), fixField.optional(), path));
} else if (FixBlock.class == annotation.annotationType()) {
for (FixFieldMeta fixFieldMeta : scanClassAndAddToDictionary(type, dictionary).getFields()) {
Field[] fieldPath = ((FixDynamicFieldMeta) fixFieldMeta).getPath();
Field[] newFieldPath = Arrays.copyOf(path, path.length + fieldPath.length);
for (int i = path.length; i < newFieldPath.length; i++) {
newFieldPath[i] = fieldPath[i - path.length];
}
fixFields.put(fixFieldMeta.getTag(), new FixDynamicFieldMeta(
fixFieldMeta.getTag(),
fixFieldMeta.isHeader(),
fixFieldMeta.isOptional(),
newFieldPath));
}
} else if (FixGroup.class == annotation.annotationType()) {
if (Collection.class.isAssignableFrom(type)) {
FixGroup fixGroup = (FixGroup) annotation;
if (!fixFields.containsKey(fixGroup.tag())) {
Class<?> componentType = getComponentType(fixGroup, f.getGenericType());
FixFieldMeta fieldMeta = isSimpleType(componentType) ?
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixFieldMeta fixFieldMeta(int tag, Object value, boolean header) {
// return new FixConstantFieldMeta(tag, header, value);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixFieldMeta.java
// public static FixGroupMeta fixGroupMeta(int groupTag,
// boolean header,
// boolean optional,
// int componentTag,
// Class<?> componentType,
// Field... path) {
// return new FixGroupMeta(groupTag, header, optional, componentTag, componentType, path);
// }
// Path: fixb/src/main/java/org/fixb/meta/FixMetaScanner.java
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.fixb.FixException;
import org.fixb.annotations.*;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import static org.fixb.meta.FixFieldMeta.fixFieldMeta;
import static org.fixb.meta.FixFieldMeta.fixGroupMeta;
final Field[] path = newPath(parentPath, f);
for (Annotation annotation : f.getDeclaredAnnotations()) {
if (FixField.class == annotation.annotationType()) {
FixField fixField = (FixField) annotation;
int tag = fixField.tag();
if (fixFields.containsKey(tag)) {
throw new FixException("There are more than one fields mapped with FIX tag [" + tag + "].");
}
fixFields.put(tag, fixFieldMeta(tag, fixField.header(), fixField.optional(), path));
} else if (FixBlock.class == annotation.annotationType()) {
for (FixFieldMeta fixFieldMeta : scanClassAndAddToDictionary(type, dictionary).getFields()) {
Field[] fieldPath = ((FixDynamicFieldMeta) fixFieldMeta).getPath();
Field[] newFieldPath = Arrays.copyOf(path, path.length + fieldPath.length);
for (int i = path.length; i < newFieldPath.length; i++) {
newFieldPath[i] = fieldPath[i - path.length];
}
fixFields.put(fixFieldMeta.getTag(), new FixDynamicFieldMeta(
fixFieldMeta.getTag(),
fixFieldMeta.isHeader(),
fixFieldMeta.isOptional(),
newFieldPath));
}
} else if (FixGroup.class == annotation.annotationType()) {
if (Collection.class.isAssignableFrom(type)) {
FixGroup fixGroup = (FixGroup) annotation;
if (!fixFields.containsKey(fixGroup.tag())) {
Class<?> componentType = getComponentType(fixGroup, f.getGenericType());
FixFieldMeta fieldMeta = isSimpleType(componentType) ?
|
fixGroupMeta(fixGroup.tag(),
|
YTEQ/fixb
|
fixb-quickfix/src/main/java/org/fixb/quickfix/QuickFixSerializer.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixSerializer.java
// public interface FixSerializer<M> {
// /**
// * Serializes the given object into FIX string.
// *
// * @param message a FIX object to serialize
// * @return a generated FIX message
// */
// String serialize(M message);
//
// /**
// * Deserializes the given FIX string into an object of the given type.
// *
// * @param fixMessage a FIX message to read
// * @return an object of the type M populated with the values from the given FIX message.
// */
// M deserialize(String fixMessage);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixMetaDictionary.java
// public interface FixMetaDictionary extends FixEnumDictionary {
// /**
// * @return all FixMessageMetas registered with the FixMetaDictionary singleton
// */
// Collection<FixMessageMeta<?>> getAllMessageMetas();
//
// /**
// * @return a FixMessageMeta for the given class. If meta has not been previously registered with this dictionary
// * it will be collected from the given class definition using {@link FixMetaScanner}.
// * @throws IllegalStateException if no meta instance found.
// * @see FixMetaScanner
// */
// <T> FixMessageMeta<T> getMetaForClass(Class<T> type);
//
// /**
// * @return a FixMessageMeta for the given FIX message type.
// * @throws IllegalStateException if no meta instance found.
// */
// <T> FixMessageMeta<T> getMetaForMessageType(String fixMessageType);
// }
|
import org.fixb.FixException;
import org.fixb.FixSerializer;
import org.fixb.meta.FixMetaDictionary;
import quickfix.ConfigError;
import quickfix.DataDictionary;
import quickfix.InvalidMessage;
import quickfix.Message;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.quickfix;
/**
* An implementation of FixSerializer that is used to serialize/deserialize quickfix.Message objects.
*
* @author vladyslav.yatsenko
*/
public class QuickFixSerializer implements FixSerializer<Message> {
private final DataDictionary dataDictionary;
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixSerializer.java
// public interface FixSerializer<M> {
// /**
// * Serializes the given object into FIX string.
// *
// * @param message a FIX object to serialize
// * @return a generated FIX message
// */
// String serialize(M message);
//
// /**
// * Deserializes the given FIX string into an object of the given type.
// *
// * @param fixMessage a FIX message to read
// * @return an object of the type M populated with the values from the given FIX message.
// */
// M deserialize(String fixMessage);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixMetaDictionary.java
// public interface FixMetaDictionary extends FixEnumDictionary {
// /**
// * @return all FixMessageMetas registered with the FixMetaDictionary singleton
// */
// Collection<FixMessageMeta<?>> getAllMessageMetas();
//
// /**
// * @return a FixMessageMeta for the given class. If meta has not been previously registered with this dictionary
// * it will be collected from the given class definition using {@link FixMetaScanner}.
// * @throws IllegalStateException if no meta instance found.
// * @see FixMetaScanner
// */
// <T> FixMessageMeta<T> getMetaForClass(Class<T> type);
//
// /**
// * @return a FixMessageMeta for the given FIX message type.
// * @throws IllegalStateException if no meta instance found.
// */
// <T> FixMessageMeta<T> getMetaForMessageType(String fixMessageType);
// }
// Path: fixb-quickfix/src/main/java/org/fixb/quickfix/QuickFixSerializer.java
import org.fixb.FixException;
import org.fixb.FixSerializer;
import org.fixb.meta.FixMetaDictionary;
import quickfix.ConfigError;
import quickfix.DataDictionary;
import quickfix.InvalidMessage;
import quickfix.Message;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.quickfix;
/**
* An implementation of FixSerializer that is used to serialize/deserialize quickfix.Message objects.
*
* @author vladyslav.yatsenko
*/
public class QuickFixSerializer implements FixSerializer<Message> {
private final DataDictionary dataDictionary;
|
public QuickFixSerializer(final String fixVersion, FixMetaDictionary fixMetaDictionary) {
|
YTEQ/fixb
|
fixb-quickfix/src/main/java/org/fixb/quickfix/QuickFixSerializer.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixSerializer.java
// public interface FixSerializer<M> {
// /**
// * Serializes the given object into FIX string.
// *
// * @param message a FIX object to serialize
// * @return a generated FIX message
// */
// String serialize(M message);
//
// /**
// * Deserializes the given FIX string into an object of the given type.
// *
// * @param fixMessage a FIX message to read
// * @return an object of the type M populated with the values from the given FIX message.
// */
// M deserialize(String fixMessage);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixMetaDictionary.java
// public interface FixMetaDictionary extends FixEnumDictionary {
// /**
// * @return all FixMessageMetas registered with the FixMetaDictionary singleton
// */
// Collection<FixMessageMeta<?>> getAllMessageMetas();
//
// /**
// * @return a FixMessageMeta for the given class. If meta has not been previously registered with this dictionary
// * it will be collected from the given class definition using {@link FixMetaScanner}.
// * @throws IllegalStateException if no meta instance found.
// * @see FixMetaScanner
// */
// <T> FixMessageMeta<T> getMetaForClass(Class<T> type);
//
// /**
// * @return a FixMessageMeta for the given FIX message type.
// * @throws IllegalStateException if no meta instance found.
// */
// <T> FixMessageMeta<T> getMetaForMessageType(String fixMessageType);
// }
|
import org.fixb.FixException;
import org.fixb.FixSerializer;
import org.fixb.meta.FixMetaDictionary;
import quickfix.ConfigError;
import quickfix.DataDictionary;
import quickfix.InvalidMessage;
import quickfix.Message;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.quickfix;
/**
* An implementation of FixSerializer that is used to serialize/deserialize quickfix.Message objects.
*
* @author vladyslav.yatsenko
*/
public class QuickFixSerializer implements FixSerializer<Message> {
private final DataDictionary dataDictionary;
public QuickFixSerializer(final String fixVersion, FixMetaDictionary fixMetaDictionary) {
this.dataDictionary = initDataDictionary(fixVersion, fixMetaDictionary);
}
@Override
public String serialize(Message message) {
return message.toString();
}
private DataDictionary initDataDictionary(final String fixVersion, FixMetaDictionary fixMetaDictionary) {
try {
return new FixMetaDataDictionary(fixVersion, fixMetaDictionary);
} catch (ConfigError e) {
throw new RuntimeException("Error loading FIX data dictionary: " + e.getMessage(), e);
}
}
@Override
@SuppressWarnings("unchecked")
public Message deserialize(String fixMessage) {
final Message message = new Message();
try {
message.fromString(fixMessage, dataDictionary, true);
} catch (InvalidMessage e) {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixSerializer.java
// public interface FixSerializer<M> {
// /**
// * Serializes the given object into FIX string.
// *
// * @param message a FIX object to serialize
// * @return a generated FIX message
// */
// String serialize(M message);
//
// /**
// * Deserializes the given FIX string into an object of the given type.
// *
// * @param fixMessage a FIX message to read
// * @return an object of the type M populated with the values from the given FIX message.
// */
// M deserialize(String fixMessage);
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixMetaDictionary.java
// public interface FixMetaDictionary extends FixEnumDictionary {
// /**
// * @return all FixMessageMetas registered with the FixMetaDictionary singleton
// */
// Collection<FixMessageMeta<?>> getAllMessageMetas();
//
// /**
// * @return a FixMessageMeta for the given class. If meta has not been previously registered with this dictionary
// * it will be collected from the given class definition using {@link FixMetaScanner}.
// * @throws IllegalStateException if no meta instance found.
// * @see FixMetaScanner
// */
// <T> FixMessageMeta<T> getMetaForClass(Class<T> type);
//
// /**
// * @return a FixMessageMeta for the given FIX message type.
// * @throws IllegalStateException if no meta instance found.
// */
// <T> FixMessageMeta<T> getMetaForMessageType(String fixMessageType);
// }
// Path: fixb-quickfix/src/main/java/org/fixb/quickfix/QuickFixSerializer.java
import org.fixb.FixException;
import org.fixb.FixSerializer;
import org.fixb.meta.FixMetaDictionary;
import quickfix.ConfigError;
import quickfix.DataDictionary;
import quickfix.InvalidMessage;
import quickfix.Message;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.quickfix;
/**
* An implementation of FixSerializer that is used to serialize/deserialize quickfix.Message objects.
*
* @author vladyslav.yatsenko
*/
public class QuickFixSerializer implements FixSerializer<Message> {
private final DataDictionary dataDictionary;
public QuickFixSerializer(final String fixVersion, FixMetaDictionary fixMetaDictionary) {
this.dataDictionary = initDataDictionary(fixVersion, fixMetaDictionary);
}
@Override
public String serialize(Message message) {
return message.toString();
}
private DataDictionary initDataDictionary(final String fixVersion, FixMetaDictionary fixMetaDictionary) {
try {
return new FixMetaDataDictionary(fixVersion, fixMetaDictionary);
} catch (ConfigError e) {
throw new RuntimeException("Error loading FIX data dictionary: " + e.getMessage(), e);
}
}
@Override
@SuppressWarnings("unchecked")
public Message deserialize(String fixMessage) {
final Message message = new Message();
try {
message.fromString(fixMessage, dataDictionary, true);
} catch (InvalidMessage e) {
|
throw new FixException(e.getMessage(), e);
|
YTEQ/fixb
|
fixb-quickfix/src/test/java/org/fixb/quickfix/test/data/TestModels.java
|
// Path: fixb-quickfix/src/test/java/org/fixb/quickfix/test/data/TestModels.java
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
|
import org.fixb.annotations.FixBlock;
import org.fixb.annotations.FixField;
import org.fixb.annotations.FixGroup;
import org.fixb.annotations.FixMessage;
import java.util.List;
import static org.fixb.quickfix.test.data.TestModels.QuoteFixFields.*;
|
this.value = value;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Component component = (Component) o;
if (value != null ? !value.equals(component.value) : component.value != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}
//////////////////////
// Quote
|
// Path: fixb-quickfix/src/test/java/org/fixb/quickfix/test/data/TestModels.java
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
// Path: fixb-quickfix/src/test/java/org/fixb/quickfix/test/data/TestModels.java
import org.fixb.annotations.FixBlock;
import org.fixb.annotations.FixField;
import org.fixb.annotations.FixGroup;
import org.fixb.annotations.FixMessage;
import java.util.List;
import static org.fixb.quickfix.test.data.TestModels.QuoteFixFields.*;
this.value = value;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Component component = (Component) o;
if (value != null ? !value.equals(component.value) : component.value != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}
//////////////////////
// Quote
|
public static final class QuoteFixFields {
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/meta/FixMetaScannerTest.java
|
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixMessage(type = "Q",
// header = @Field(tag = HDR, value = "TEST"),
// body = {@Field(tag = 18, value = "BODY1"),
// @Field(tag = 19, value = "BODY2")})
// public class SampleQuote extends TestModels.BasicQuote {
//
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
//
// @FixField(tag = SIDE)
// private final Side side;
//
// @FixField(tag = SYMBOL)
// private final String symbol;
//
// @FixGroup(tag = AMOUNT_GR, componentTag = AMOUNT, component = Integer.class)
// private final List amounts;
//
// @FixGroup(tag = PARAM_GR, component = TestModels.Params.class)
// private final List<TestModels.Params> paramsList;
//
// @FixBlock
// private final TestModels.Params params;
//
// public SampleQuote(
// @FixField(tag = QUOTE_ID) final String quoteId,
// @FixField(tag = SIDE) final Side side,
// @FixField(tag = SYMBOL) final String symbol,
// @FixField(tag = AMOUNT_GR) final List<Integer> amounts,
// @FixField(tag = PARAM_GR) final List<TestModels.Params> paramsList,
// @FixBlock final TestModels.Params params) {
// super(quoteId);
// this.side = side;
// this.symbol = symbol;
// this.amounts = amounts;
// this.paramsList = paramsList;
// this.params = params;
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public Side getSide() {
// return side;
// }
//
// public List getAmounts() {
// return amounts;
// }
//
// public TestModels.Params getParams() {
// return params;
// }
//
// public List<TestModels.Params> getParamsList() {
// return paramsList;
// }
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// public final class TestModels {
// @FixMessage(type = "M1")
// public static class Message1 {
// @FixBlock
// public final Component component;
//
// public Message1(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixMessage(type = "M2")
// public static class Message2 {
// @FixBlock
// public final Component component;
//
// public Message2(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixBlock
// public static class Component {
// @FixField(tag = 100)
// public final String value;
//
// public Component(@FixField(tag = 100) final String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Component component = (Component) o;
//
// if (value != null ? !value.equals(component.value) : component.value != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return value != null ? value.hashCode() : 0;
// }
// }
//
// //////////////////////
// // Quote
//
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
//
// public abstract static class BasicQuote {
// @FixField(tag = QUOTE_ID)
// private final String quoteId;
//
// public BasicQuote(@FixField(tag = QUOTE_ID) final String quoteId) {
// this.quoteId = quoteId;
// }
//
// public String getQuoteId() {
// return quoteId;
// }
// }
//
// @FixBlock
// public static class Params {
// @FixField(tag = P1)
// private final String param1;
// @FixField(tag = P2)
// private final String param2;
//
// public Params(@FixField(tag = P1) final String param1,
// @FixField(tag = P2) final String param2) {
// this.param1 = param1;
// this.param2 = param2;
// }
//
// public String getParam1() {
// return param1;
// }
//
// public String getParam2() {
// return param2;
// }
// }
//
// }
|
import org.fixb.test.data.SampleQuote;
import org.fixb.test.data.TestModels;
import org.junit.Test;
import static org.junit.Assert.*;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.meta;
public class FixMetaScannerTest {
@Test
public void canFindAndLoadFixClassesInAPackage() {
// When
final FixMetaDictionary fixMetaDictionary = FixMetaScanner.scanClassesIn("org.fixb.test.data");
// Then
assertNotNull(fixMetaDictionary.getMetaForMessageType("Q"));
assertNotNull(fixMetaDictionary.getMetaForMessageType("M1"));
assertNotNull(fixMetaDictionary.getMetaForMessageType("M2"));
|
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixMessage(type = "Q",
// header = @Field(tag = HDR, value = "TEST"),
// body = {@Field(tag = 18, value = "BODY1"),
// @Field(tag = 19, value = "BODY2")})
// public class SampleQuote extends TestModels.BasicQuote {
//
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
//
// @FixField(tag = SIDE)
// private final Side side;
//
// @FixField(tag = SYMBOL)
// private final String symbol;
//
// @FixGroup(tag = AMOUNT_GR, componentTag = AMOUNT, component = Integer.class)
// private final List amounts;
//
// @FixGroup(tag = PARAM_GR, component = TestModels.Params.class)
// private final List<TestModels.Params> paramsList;
//
// @FixBlock
// private final TestModels.Params params;
//
// public SampleQuote(
// @FixField(tag = QUOTE_ID) final String quoteId,
// @FixField(tag = SIDE) final Side side,
// @FixField(tag = SYMBOL) final String symbol,
// @FixField(tag = AMOUNT_GR) final List<Integer> amounts,
// @FixField(tag = PARAM_GR) final List<TestModels.Params> paramsList,
// @FixBlock final TestModels.Params params) {
// super(quoteId);
// this.side = side;
// this.symbol = symbol;
// this.amounts = amounts;
// this.paramsList = paramsList;
// this.params = params;
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public Side getSide() {
// return side;
// }
//
// public List getAmounts() {
// return amounts;
// }
//
// public TestModels.Params getParams() {
// return params;
// }
//
// public List<TestModels.Params> getParamsList() {
// return paramsList;
// }
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// public final class TestModels {
// @FixMessage(type = "M1")
// public static class Message1 {
// @FixBlock
// public final Component component;
//
// public Message1(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixMessage(type = "M2")
// public static class Message2 {
// @FixBlock
// public final Component component;
//
// public Message2(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixBlock
// public static class Component {
// @FixField(tag = 100)
// public final String value;
//
// public Component(@FixField(tag = 100) final String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Component component = (Component) o;
//
// if (value != null ? !value.equals(component.value) : component.value != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return value != null ? value.hashCode() : 0;
// }
// }
//
// //////////////////////
// // Quote
//
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
//
// public abstract static class BasicQuote {
// @FixField(tag = QUOTE_ID)
// private final String quoteId;
//
// public BasicQuote(@FixField(tag = QUOTE_ID) final String quoteId) {
// this.quoteId = quoteId;
// }
//
// public String getQuoteId() {
// return quoteId;
// }
// }
//
// @FixBlock
// public static class Params {
// @FixField(tag = P1)
// private final String param1;
// @FixField(tag = P2)
// private final String param2;
//
// public Params(@FixField(tag = P1) final String param1,
// @FixField(tag = P2) final String param2) {
// this.param1 = param1;
// this.param2 = param2;
// }
//
// public String getParam1() {
// return param1;
// }
//
// public String getParam2() {
// return param2;
// }
// }
//
// }
// Path: fixb/src/test/java/org/fixb/meta/FixMetaScannerTest.java
import org.fixb.test.data.SampleQuote;
import org.fixb.test.data.TestModels;
import org.junit.Test;
import static org.junit.Assert.*;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.meta;
public class FixMetaScannerTest {
@Test
public void canFindAndLoadFixClassesInAPackage() {
// When
final FixMetaDictionary fixMetaDictionary = FixMetaScanner.scanClassesIn("org.fixb.test.data");
// Then
assertNotNull(fixMetaDictionary.getMetaForMessageType("Q"));
assertNotNull(fixMetaDictionary.getMetaForMessageType("M1"));
assertNotNull(fixMetaDictionary.getMetaForMessageType("M2"));
|
assertNotNull(fixMetaDictionary.getMetaForClass(SampleQuote.class));
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/meta/FixMetaScannerTest.java
|
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixMessage(type = "Q",
// header = @Field(tag = HDR, value = "TEST"),
// body = {@Field(tag = 18, value = "BODY1"),
// @Field(tag = 19, value = "BODY2")})
// public class SampleQuote extends TestModels.BasicQuote {
//
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
//
// @FixField(tag = SIDE)
// private final Side side;
//
// @FixField(tag = SYMBOL)
// private final String symbol;
//
// @FixGroup(tag = AMOUNT_GR, componentTag = AMOUNT, component = Integer.class)
// private final List amounts;
//
// @FixGroup(tag = PARAM_GR, component = TestModels.Params.class)
// private final List<TestModels.Params> paramsList;
//
// @FixBlock
// private final TestModels.Params params;
//
// public SampleQuote(
// @FixField(tag = QUOTE_ID) final String quoteId,
// @FixField(tag = SIDE) final Side side,
// @FixField(tag = SYMBOL) final String symbol,
// @FixField(tag = AMOUNT_GR) final List<Integer> amounts,
// @FixField(tag = PARAM_GR) final List<TestModels.Params> paramsList,
// @FixBlock final TestModels.Params params) {
// super(quoteId);
// this.side = side;
// this.symbol = symbol;
// this.amounts = amounts;
// this.paramsList = paramsList;
// this.params = params;
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public Side getSide() {
// return side;
// }
//
// public List getAmounts() {
// return amounts;
// }
//
// public TestModels.Params getParams() {
// return params;
// }
//
// public List<TestModels.Params> getParamsList() {
// return paramsList;
// }
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// public final class TestModels {
// @FixMessage(type = "M1")
// public static class Message1 {
// @FixBlock
// public final Component component;
//
// public Message1(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixMessage(type = "M2")
// public static class Message2 {
// @FixBlock
// public final Component component;
//
// public Message2(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixBlock
// public static class Component {
// @FixField(tag = 100)
// public final String value;
//
// public Component(@FixField(tag = 100) final String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Component component = (Component) o;
//
// if (value != null ? !value.equals(component.value) : component.value != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return value != null ? value.hashCode() : 0;
// }
// }
//
// //////////////////////
// // Quote
//
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
//
// public abstract static class BasicQuote {
// @FixField(tag = QUOTE_ID)
// private final String quoteId;
//
// public BasicQuote(@FixField(tag = QUOTE_ID) final String quoteId) {
// this.quoteId = quoteId;
// }
//
// public String getQuoteId() {
// return quoteId;
// }
// }
//
// @FixBlock
// public static class Params {
// @FixField(tag = P1)
// private final String param1;
// @FixField(tag = P2)
// private final String param2;
//
// public Params(@FixField(tag = P1) final String param1,
// @FixField(tag = P2) final String param2) {
// this.param1 = param1;
// this.param2 = param2;
// }
//
// public String getParam1() {
// return param1;
// }
//
// public String getParam2() {
// return param2;
// }
// }
//
// }
|
import org.fixb.test.data.SampleQuote;
import org.fixb.test.data.TestModels;
import org.junit.Test;
import static org.junit.Assert.*;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.meta;
public class FixMetaScannerTest {
@Test
public void canFindAndLoadFixClassesInAPackage() {
// When
final FixMetaDictionary fixMetaDictionary = FixMetaScanner.scanClassesIn("org.fixb.test.data");
// Then
assertNotNull(fixMetaDictionary.getMetaForMessageType("Q"));
assertNotNull(fixMetaDictionary.getMetaForMessageType("M1"));
assertNotNull(fixMetaDictionary.getMetaForMessageType("M2"));
assertNotNull(fixMetaDictionary.getMetaForClass(SampleQuote.class));
|
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixMessage(type = "Q",
// header = @Field(tag = HDR, value = "TEST"),
// body = {@Field(tag = 18, value = "BODY1"),
// @Field(tag = 19, value = "BODY2")})
// public class SampleQuote extends TestModels.BasicQuote {
//
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
//
// @FixField(tag = SIDE)
// private final Side side;
//
// @FixField(tag = SYMBOL)
// private final String symbol;
//
// @FixGroup(tag = AMOUNT_GR, componentTag = AMOUNT, component = Integer.class)
// private final List amounts;
//
// @FixGroup(tag = PARAM_GR, component = TestModels.Params.class)
// private final List<TestModels.Params> paramsList;
//
// @FixBlock
// private final TestModels.Params params;
//
// public SampleQuote(
// @FixField(tag = QUOTE_ID) final String quoteId,
// @FixField(tag = SIDE) final Side side,
// @FixField(tag = SYMBOL) final String symbol,
// @FixField(tag = AMOUNT_GR) final List<Integer> amounts,
// @FixField(tag = PARAM_GR) final List<TestModels.Params> paramsList,
// @FixBlock final TestModels.Params params) {
// super(quoteId);
// this.side = side;
// this.symbol = symbol;
// this.amounts = amounts;
// this.paramsList = paramsList;
// this.params = params;
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public Side getSide() {
// return side;
// }
//
// public List getAmounts() {
// return amounts;
// }
//
// public TestModels.Params getParams() {
// return params;
// }
//
// public List<TestModels.Params> getParamsList() {
// return paramsList;
// }
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// public final class TestModels {
// @FixMessage(type = "M1")
// public static class Message1 {
// @FixBlock
// public final Component component;
//
// public Message1(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixMessage(type = "M2")
// public static class Message2 {
// @FixBlock
// public final Component component;
//
// public Message2(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixBlock
// public static class Component {
// @FixField(tag = 100)
// public final String value;
//
// public Component(@FixField(tag = 100) final String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Component component = (Component) o;
//
// if (value != null ? !value.equals(component.value) : component.value != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return value != null ? value.hashCode() : 0;
// }
// }
//
// //////////////////////
// // Quote
//
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
//
// public abstract static class BasicQuote {
// @FixField(tag = QUOTE_ID)
// private final String quoteId;
//
// public BasicQuote(@FixField(tag = QUOTE_ID) final String quoteId) {
// this.quoteId = quoteId;
// }
//
// public String getQuoteId() {
// return quoteId;
// }
// }
//
// @FixBlock
// public static class Params {
// @FixField(tag = P1)
// private final String param1;
// @FixField(tag = P2)
// private final String param2;
//
// public Params(@FixField(tag = P1) final String param1,
// @FixField(tag = P2) final String param2) {
// this.param1 = param1;
// this.param2 = param2;
// }
//
// public String getParam1() {
// return param1;
// }
//
// public String getParam2() {
// return param2;
// }
// }
//
// }
// Path: fixb/src/test/java/org/fixb/meta/FixMetaScannerTest.java
import org.fixb.test.data.SampleQuote;
import org.fixb.test.data.TestModels;
import org.junit.Test;
import static org.junit.Assert.*;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.meta;
public class FixMetaScannerTest {
@Test
public void canFindAndLoadFixClassesInAPackage() {
// When
final FixMetaDictionary fixMetaDictionary = FixMetaScanner.scanClassesIn("org.fixb.test.data");
// Then
assertNotNull(fixMetaDictionary.getMetaForMessageType("Q"));
assertNotNull(fixMetaDictionary.getMetaForMessageType("M1"));
assertNotNull(fixMetaDictionary.getMetaForMessageType("M2"));
assertNotNull(fixMetaDictionary.getMetaForClass(SampleQuote.class));
|
assertNotNull(fixMetaDictionary.getMetaForClass(TestModels.Message1.class));
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/adapter/GenericFixAdapterTest.java
|
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// public final class TestModels {
// @FixMessage(type = "M1")
// public static class Message1 {
// @FixBlock
// public final Component component;
//
// public Message1(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixMessage(type = "M2")
// public static class Message2 {
// @FixBlock
// public final Component component;
//
// public Message2(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixBlock
// public static class Component {
// @FixField(tag = 100)
// public final String value;
//
// public Component(@FixField(tag = 100) final String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Component component = (Component) o;
//
// if (value != null ? !value.equals(component.value) : component.value != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return value != null ? value.hashCode() : 0;
// }
// }
//
// //////////////////////
// // Quote
//
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
//
// public abstract static class BasicQuote {
// @FixField(tag = QUOTE_ID)
// private final String quoteId;
//
// public BasicQuote(@FixField(tag = QUOTE_ID) final String quoteId) {
// this.quoteId = quoteId;
// }
//
// public String getQuoteId() {
// return quoteId;
// }
// }
//
// @FixBlock
// public static class Params {
// @FixField(tag = P1)
// private final String param1;
// @FixField(tag = P2)
// private final String param2;
//
// public Params(@FixField(tag = P1) final String param1,
// @FixField(tag = P2) final String param2) {
// this.param1 = param1;
// this.param2 = param2;
// }
//
// public String getParam1() {
// return param1;
// }
//
// public String getParam2() {
// return param2;
// }
// }
//
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// @FixMessage(type = "M1")
// public static class Message1 {
// @FixBlock
// public final Component component;
//
// public Message1(@FixBlock final Component component) {
// this.component = component;
// }
// }
|
import org.fixb.test.data.TestModels;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static junit.framework.Assert.assertEquals;
import static org.fixb.test.data.TestModels.Message1;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.adapter;
public class GenericFixAdapterTest extends AbstractFixAdapterTest {
final GenericFixAdapter<Message1, Map<Integer, Object>> adapter =
new GenericFixAdapter<Message1, Map<Integer, Object>>("FIX.4.4",
fixFieldExtractor, builderFactory, fixMetaDictionary.getMetaForClass(Message1.class)
);
@Test
public void testFromFixType1() {
// Given
final Map<Integer, Object> fixMessage = new HashMap<Integer, Object>();
fixMessage.put(35, "M1");
fixMessage.put(100, "VALUE");
// When
Message1 object = adapter.fromFix(fixMessage);
// Then
assertEquals("VALUE", object.component.value);
}
@Test
public void testToFix() {
// Given
|
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// public final class TestModels {
// @FixMessage(type = "M1")
// public static class Message1 {
// @FixBlock
// public final Component component;
//
// public Message1(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixMessage(type = "M2")
// public static class Message2 {
// @FixBlock
// public final Component component;
//
// public Message2(@FixBlock final Component component) {
// this.component = component;
// }
// }
//
// @FixBlock
// public static class Component {
// @FixField(tag = 100)
// public final String value;
//
// public Component(@FixField(tag = 100) final String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Component component = (Component) o;
//
// if (value != null ? !value.equals(component.value) : component.value != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return value != null ? value.hashCode() : 0;
// }
// }
//
// //////////////////////
// // Quote
//
// public static final class QuoteFixFields {
// public static final int QUOTE_ID = 11;
// public static final int SYMBOL = 12;
// public static final int AMOUNT_GR = 13;
// public static final int AMOUNT = 14;
// public static final int PARAM_GR = 20;
// public static final int P1 = 21;
// public static final int P2 = 22;
// public static final int HDR = 33;
// public static final int SIDE = 40;
// }
//
// public abstract static class BasicQuote {
// @FixField(tag = QUOTE_ID)
// private final String quoteId;
//
// public BasicQuote(@FixField(tag = QUOTE_ID) final String quoteId) {
// this.quoteId = quoteId;
// }
//
// public String getQuoteId() {
// return quoteId;
// }
// }
//
// @FixBlock
// public static class Params {
// @FixField(tag = P1)
// private final String param1;
// @FixField(tag = P2)
// private final String param2;
//
// public Params(@FixField(tag = P1) final String param1,
// @FixField(tag = P2) final String param2) {
// this.param1 = param1;
// this.param2 = param2;
// }
//
// public String getParam1() {
// return param1;
// }
//
// public String getParam2() {
// return param2;
// }
// }
//
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/TestModels.java
// @FixMessage(type = "M1")
// public static class Message1 {
// @FixBlock
// public final Component component;
//
// public Message1(@FixBlock final Component component) {
// this.component = component;
// }
// }
// Path: fixb/src/test/java/org/fixb/adapter/GenericFixAdapterTest.java
import org.fixb.test.data.TestModels;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static junit.framework.Assert.assertEquals;
import static org.fixb.test.data.TestModels.Message1;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.adapter;
public class GenericFixAdapterTest extends AbstractFixAdapterTest {
final GenericFixAdapter<Message1, Map<Integer, Object>> adapter =
new GenericFixAdapter<Message1, Map<Integer, Object>>("FIX.4.4",
fixFieldExtractor, builderFactory, fixMetaDictionary.getMetaForClass(Message1.class)
);
@Test
public void testFromFixType1() {
// Given
final Map<Integer, Object> fixMessage = new HashMap<Integer, Object>();
fixMessage.put(35, "M1");
fixMessage.put(100, "VALUE");
// When
Message1 object = adapter.fromFix(fixMessage);
// Then
assertEquals("VALUE", object.component.value);
}
@Test
public void testToFix() {
// Given
|
Message1 object = new Message1(new TestModels.Component("VALUE"));
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/impl/CollectionFactory.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
|
import org.fixb.FixException;
import java.lang.reflect.Modifier;
import java.util.*;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
* A static factory for Collection types.
*
* @author vladyslav.yatsenko
*/
public class CollectionFactory {
/**
* Creates an empty instance of the given collection type.
* If the given an class in an interface, an ArrayList will be created for java.util.List
* or java.util.Collection interfaces, and HashSet for java.util.Set interface.
*/
@SuppressWarnings("unchecked")
public static <T extends Collection<?>> T createCollection(Class<T> collClass) {
if (!collClass.isInterface() && !Modifier.isAbstract(collClass.getModifiers())) {
try {
return collClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
// Path: fixb/src/main/java/org/fixb/impl/CollectionFactory.java
import org.fixb.FixException;
import java.lang.reflect.Modifier;
import java.util.*;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
* A static factory for Collection types.
*
* @author vladyslav.yatsenko
*/
public class CollectionFactory {
/**
* Creates an empty instance of the given collection type.
* If the given an class in an interface, an ArrayList will be created for java.util.List
* or java.util.Collection interfaces, and HashSet for java.util.Set interface.
*/
@SuppressWarnings("unchecked")
public static <T extends Collection<?>> T createCollection(Class<T> collClass) {
if (!collClass.isInterface() && !Modifier.isAbstract(collClass.getModifiers())) {
try {
return collClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
|
throw new FixException(e.getMessage(), e);
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/meta/FixDynamicFieldMeta.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
|
import org.fixb.FixException;
import java.lang.reflect.Field;
|
}
/**
* @return the type of this field's value
*/
public Class<?> getType() {
return type;
}
/**
* @return false.
*/
public boolean isGroup() {
return false;
}
/**
* Resolves the field's value using the given object.
*
* @param o the object containing the field's value
* @return this field's value from the given object.
*/
public Object getValue(Object o) {
try {
Object value = o;
for (Field f : path) {
value = f.get(value);
}
return value;
} catch (IllegalAccessException e) {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
// Path: fixb/src/main/java/org/fixb/meta/FixDynamicFieldMeta.java
import org.fixb.FixException;
import java.lang.reflect.Field;
}
/**
* @return the type of this field's value
*/
public Class<?> getType() {
return type;
}
/**
* @return false.
*/
public boolean isGroup() {
return false;
}
/**
* Resolves the field's value using the given object.
*
* @param o the object containing the field's value
* @return this field's value from the given object.
*/
public Object getValue(Object o) {
try {
Object value = o;
for (Field f : path) {
value = f.get(value);
}
return value;
} catch (IllegalAccessException e) {
|
throw new FixException("Error while reading tag from path: " + getPathString(), e);
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/impl/FieldCursor.java
|
// Path: fixb/src/main/java/org/fixb/impl/FormatConstants.java
// public static final char SOH = 0x01;
|
import java.util.HashMap;
import java.util.Map;
import static org.fixb.impl.FormatConstants.SOH;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
* Can extract separate tag values from a FIX message string while keeping track of the read position in it. It is used
* in the implementation of NativeFixFieldExtractor.
*
* @author vladyslav.yatsenko
*/
public class FieldCursor {
private Map<Integer, String> buffer = new HashMap<Integer, String>();
private int lastPosition = -1;
private int lastTag;
final String fixMessage;
String lastValue;
/**
* A static factory method.
*
* @param fixMessage a string representing FIX message
* @return a new instance of FieldCursor based on the given FIX message.
*/
public static FieldCursor create(String fixMessage) {
return new FieldCursor(fixMessage);
}
/**
* @return the last read FIX field value.
*/
public String lastValue() {
return lastValue;
}
/**
* @return the last read FIX tag.
*/
public int lastTag() {
return lastTag;
}
/**
* Reads the next FIX field in the message and updates the last read field tag and value if available.
*
* @return <code>true</code> if next field could be read, <code>false</code> if reached the end of message.
*/
public boolean nextField() {
final int start = lastPosition == -1 ? 0 : lastPosition;
final int interim = fixMessage.indexOf('=', start);
if (interim == -1) {
lastTag = 0;
lastValue = null;
lastPosition = fixMessage.length();
return false;
}
|
// Path: fixb/src/main/java/org/fixb/impl/FormatConstants.java
// public static final char SOH = 0x01;
// Path: fixb/src/main/java/org/fixb/impl/FieldCursor.java
import java.util.HashMap;
import java.util.Map;
import static org.fixb.impl.FormatConstants.SOH;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
* Can extract separate tag values from a FIX message string while keeping track of the read position in it. It is used
* in the implementation of NativeFixFieldExtractor.
*
* @author vladyslav.yatsenko
*/
public class FieldCursor {
private Map<Integer, String> buffer = new HashMap<Integer, String>();
private int lastPosition = -1;
private int lastTag;
final String fixMessage;
String lastValue;
/**
* A static factory method.
*
* @param fixMessage a string representing FIX message
* @return a new instance of FieldCursor based on the given FIX message.
*/
public static FieldCursor create(String fixMessage) {
return new FieldCursor(fixMessage);
}
/**
* @return the last read FIX field value.
*/
public String lastValue() {
return lastValue;
}
/**
* @return the last read FIX tag.
*/
public int lastTag() {
return lastTag;
}
/**
* Reads the next FIX field in the message and updates the last read field tag and value if available.
*
* @return <code>true</code> if next field could be read, <code>false</code> if reached the end of message.
*/
public boolean nextField() {
final int start = lastPosition == -1 ? 0 : lastPosition;
final int interim = fixMessage.indexOf('=', start);
if (interim == -1) {
lastTag = 0;
lastValue = null;
lastPosition = fixMessage.length();
return false;
}
|
final int end = fixMessage.indexOf(SOH, interim + 1);
|
YTEQ/fixb
|
fixb-quickfix/src/main/java/org/fixb/quickfix/QuickFixFieldExtractor.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixFieldExtractor.java
// public interface FixFieldExtractor<M> {
//
// /**
// * Reads a tag of the FIX field identified by the given tag. If optional is true then in case of not found field
// * null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage a FIX message object
// * @param type a type to return
// * @param tag a FIX field tag to read the tag from
// * @param optional determines whether a not found field should generate an exception
// * @param <T> the type of the result
// * @throws FixException
// */
// <T> T getFieldValue(M fixMessage, Class<T> type, int tag, boolean optional);
//
// /**
// * Reads all repeating groups from the given FIX message identified by the given tag. If optional is true then in
// * case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param elementType type of the resulting collection elements (has the same meaning as the type parameter in
// * getFieldValue)
// * @param elementTag the group delimiter tag (or the tag of a single element)
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// Class<T> elementType,
// int elementTag,
// boolean optional);
//
// /**
// * Reads all repeating block groups from the given FIX message identified by the given tag. If optional is true
// * then in case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param componentMeta the FIX mapping metadata for a single repeating group
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// FixBlockMeta<T> componentMeta,
// boolean optional);
// }
//
// Path: fixb/src/main/java/org/fixb/impl/CollectionFactory.java
// public class CollectionFactory {
// /**
// * Creates an empty instance of the given collection type.
// * If the given an class in an interface, an ArrayList will be created for java.util.List
// * or java.util.Collection interfaces, and HashSet for java.util.Set interface.
// */
// @SuppressWarnings("unchecked")
// public static <T extends Collection<?>> T createCollection(Class<T> collClass) {
// if (!collClass.isInterface() && !Modifier.isAbstract(collClass.getModifiers())) {
// try {
// return collClass.newInstance();
// } catch (InstantiationException | IllegalAccessException e) {
// throw new FixException(e.getMessage(), e);
// }
// } else if (List.class.isAssignableFrom(collClass)) {
// return (T) new ArrayList<>();
// } else if (Set.class.isAssignableFrom(collClass)) {
// return (T) new HashSet<>();
// } else if (Collection.class.isAssignableFrom(collClass)) {
// return (T) new ArrayList<>();
// } else {
// throw new IllegalArgumentException("Unknown collection type: " + collClass);
// }
// }
// }
|
import org.fixb.FixException;
import org.fixb.FixFieldExtractor;
import org.fixb.impl.CollectionFactory;
import org.fixb.meta.*;
import org.joda.time.*;
import org.joda.time.format.DateTimeFormatterBuilder;
import quickfix.*;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.quickfix;
/**
* An implementation of FixFieldExtractor that is used to extract data from quickfix.Message objects.
*
* @author vladyslav.yatsenko
* @see quickfix.Message
*/
public class QuickFixFieldExtractor implements FixFieldExtractor<Message> {
@Override
public <T> T getFieldValue(Message message, Class<T> type, int tag, boolean optional) {
T fieldValue = getFieldValueFromMap(message, type, tag);
if (fieldValue == null) {
if (!optional) {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixFieldExtractor.java
// public interface FixFieldExtractor<M> {
//
// /**
// * Reads a tag of the FIX field identified by the given tag. If optional is true then in case of not found field
// * null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage a FIX message object
// * @param type a type to return
// * @param tag a FIX field tag to read the tag from
// * @param optional determines whether a not found field should generate an exception
// * @param <T> the type of the result
// * @throws FixException
// */
// <T> T getFieldValue(M fixMessage, Class<T> type, int tag, boolean optional);
//
// /**
// * Reads all repeating groups from the given FIX message identified by the given tag. If optional is true then in
// * case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param elementType type of the resulting collection elements (has the same meaning as the type parameter in
// * getFieldValue)
// * @param elementTag the group delimiter tag (or the tag of a single element)
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// Class<T> elementType,
// int elementTag,
// boolean optional);
//
// /**
// * Reads all repeating block groups from the given FIX message identified by the given tag. If optional is true
// * then in case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param componentMeta the FIX mapping metadata for a single repeating group
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// FixBlockMeta<T> componentMeta,
// boolean optional);
// }
//
// Path: fixb/src/main/java/org/fixb/impl/CollectionFactory.java
// public class CollectionFactory {
// /**
// * Creates an empty instance of the given collection type.
// * If the given an class in an interface, an ArrayList will be created for java.util.List
// * or java.util.Collection interfaces, and HashSet for java.util.Set interface.
// */
// @SuppressWarnings("unchecked")
// public static <T extends Collection<?>> T createCollection(Class<T> collClass) {
// if (!collClass.isInterface() && !Modifier.isAbstract(collClass.getModifiers())) {
// try {
// return collClass.newInstance();
// } catch (InstantiationException | IllegalAccessException e) {
// throw new FixException(e.getMessage(), e);
// }
// } else if (List.class.isAssignableFrom(collClass)) {
// return (T) new ArrayList<>();
// } else if (Set.class.isAssignableFrom(collClass)) {
// return (T) new HashSet<>();
// } else if (Collection.class.isAssignableFrom(collClass)) {
// return (T) new ArrayList<>();
// } else {
// throw new IllegalArgumentException("Unknown collection type: " + collClass);
// }
// }
// }
// Path: fixb-quickfix/src/main/java/org/fixb/quickfix/QuickFixFieldExtractor.java
import org.fixb.FixException;
import org.fixb.FixFieldExtractor;
import org.fixb.impl.CollectionFactory;
import org.fixb.meta.*;
import org.joda.time.*;
import org.joda.time.format.DateTimeFormatterBuilder;
import quickfix.*;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.quickfix;
/**
* An implementation of FixFieldExtractor that is used to extract data from quickfix.Message objects.
*
* @author vladyslav.yatsenko
* @see quickfix.Message
*/
public class QuickFixFieldExtractor implements FixFieldExtractor<Message> {
@Override
public <T> T getFieldValue(Message message, Class<T> type, int tag, boolean optional) {
T fieldValue = getFieldValueFromMap(message, type, tag);
if (fieldValue == null) {
if (!optional) {
|
throw new FixException("Field [" + tag + "] was not found in message");
|
YTEQ/fixb
|
fixb-quickfix/src/main/java/org/fixb/quickfix/QuickFixFieldExtractor.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixFieldExtractor.java
// public interface FixFieldExtractor<M> {
//
// /**
// * Reads a tag of the FIX field identified by the given tag. If optional is true then in case of not found field
// * null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage a FIX message object
// * @param type a type to return
// * @param tag a FIX field tag to read the tag from
// * @param optional determines whether a not found field should generate an exception
// * @param <T> the type of the result
// * @throws FixException
// */
// <T> T getFieldValue(M fixMessage, Class<T> type, int tag, boolean optional);
//
// /**
// * Reads all repeating groups from the given FIX message identified by the given tag. If optional is true then in
// * case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param elementType type of the resulting collection elements (has the same meaning as the type parameter in
// * getFieldValue)
// * @param elementTag the group delimiter tag (or the tag of a single element)
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// Class<T> elementType,
// int elementTag,
// boolean optional);
//
// /**
// * Reads all repeating block groups from the given FIX message identified by the given tag. If optional is true
// * then in case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param componentMeta the FIX mapping metadata for a single repeating group
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// FixBlockMeta<T> componentMeta,
// boolean optional);
// }
//
// Path: fixb/src/main/java/org/fixb/impl/CollectionFactory.java
// public class CollectionFactory {
// /**
// * Creates an empty instance of the given collection type.
// * If the given an class in an interface, an ArrayList will be created for java.util.List
// * or java.util.Collection interfaces, and HashSet for java.util.Set interface.
// */
// @SuppressWarnings("unchecked")
// public static <T extends Collection<?>> T createCollection(Class<T> collClass) {
// if (!collClass.isInterface() && !Modifier.isAbstract(collClass.getModifiers())) {
// try {
// return collClass.newInstance();
// } catch (InstantiationException | IllegalAccessException e) {
// throw new FixException(e.getMessage(), e);
// }
// } else if (List.class.isAssignableFrom(collClass)) {
// return (T) new ArrayList<>();
// } else if (Set.class.isAssignableFrom(collClass)) {
// return (T) new HashSet<>();
// } else if (Collection.class.isAssignableFrom(collClass)) {
// return (T) new ArrayList<>();
// } else {
// throw new IllegalArgumentException("Unknown collection type: " + collClass);
// }
// }
// }
|
import org.fixb.FixException;
import org.fixb.FixFieldExtractor;
import org.fixb.impl.CollectionFactory;
import org.fixb.meta.*;
import org.joda.time.*;
import org.joda.time.format.DateTimeFormatterBuilder;
import quickfix.*;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
|
groups = getGroupsFromMap(fixMessage.getHeader(), type, groupTag, elementType, elementTag);
}
if (!optional && groups.isEmpty()) {
throw new FixException("Group [" + groupTag + "] was not found in message");
}
return groups;
}
@Override
public <T, C extends Collection<T>> C getGroups(Message fixMessage,
Class<C> type,
int groupTag,
FixBlockMeta<T> componentMeta,
boolean optional) {
C groups = getGroupsFromMap(fixMessage, type, groupTag, componentMeta);
if (groups.isEmpty()) {
groups = getGroupsFromMap(fixMessage.getHeader(), type, groupTag, componentMeta);
}
if (!optional && groups.isEmpty()) {
throw new FixException("Group [" + groupTag + "] was not found in message");
}
return groups;
}
@SuppressWarnings("unchecked")
private <T, C extends Collection<T>> C getGroupsFromMap(FieldMap fieldMap,
Class<C> type,
int tag,
FixBlockMeta<T> componentMeta) {
try {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/FixFieldExtractor.java
// public interface FixFieldExtractor<M> {
//
// /**
// * Reads a tag of the FIX field identified by the given tag. If optional is true then in case of not found field
// * null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage a FIX message object
// * @param type a type to return
// * @param tag a FIX field tag to read the tag from
// * @param optional determines whether a not found field should generate an exception
// * @param <T> the type of the result
// * @throws FixException
// */
// <T> T getFieldValue(M fixMessage, Class<T> type, int tag, boolean optional);
//
// /**
// * Reads all repeating groups from the given FIX message identified by the given tag. If optional is true then in
// * case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param elementType type of the resulting collection elements (has the same meaning as the type parameter in
// * getFieldValue)
// * @param elementTag the group delimiter tag (or the tag of a single element)
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// Class<T> elementType,
// int elementTag,
// boolean optional);
//
// /**
// * Reads all repeating block groups from the given FIX message identified by the given tag. If optional is true
// * then in case of
// * non found groups null will be returned, otherwise should throw a FixException.
// *
// * @param fixMessage the FIX message object
// * @param type the collection type to return
// * @param groupTag the FIX group tag to read from
// * @param componentMeta the FIX mapping metadata for a single repeating group
// * @param optional determines whether a not found group should generate an exception
// * @param <T> type or the resulting collection elements
// */
// <T, C extends Collection<T>> C getGroups(M fixMessage,
// Class<C> type,
// int groupTag,
// FixBlockMeta<T> componentMeta,
// boolean optional);
// }
//
// Path: fixb/src/main/java/org/fixb/impl/CollectionFactory.java
// public class CollectionFactory {
// /**
// * Creates an empty instance of the given collection type.
// * If the given an class in an interface, an ArrayList will be created for java.util.List
// * or java.util.Collection interfaces, and HashSet for java.util.Set interface.
// */
// @SuppressWarnings("unchecked")
// public static <T extends Collection<?>> T createCollection(Class<T> collClass) {
// if (!collClass.isInterface() && !Modifier.isAbstract(collClass.getModifiers())) {
// try {
// return collClass.newInstance();
// } catch (InstantiationException | IllegalAccessException e) {
// throw new FixException(e.getMessage(), e);
// }
// } else if (List.class.isAssignableFrom(collClass)) {
// return (T) new ArrayList<>();
// } else if (Set.class.isAssignableFrom(collClass)) {
// return (T) new HashSet<>();
// } else if (Collection.class.isAssignableFrom(collClass)) {
// return (T) new ArrayList<>();
// } else {
// throw new IllegalArgumentException("Unknown collection type: " + collClass);
// }
// }
// }
// Path: fixb-quickfix/src/main/java/org/fixb/quickfix/QuickFixFieldExtractor.java
import org.fixb.FixException;
import org.fixb.FixFieldExtractor;
import org.fixb.impl.CollectionFactory;
import org.fixb.meta.*;
import org.joda.time.*;
import org.joda.time.format.DateTimeFormatterBuilder;
import quickfix.*;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
groups = getGroupsFromMap(fixMessage.getHeader(), type, groupTag, elementType, elementTag);
}
if (!optional && groups.isEmpty()) {
throw new FixException("Group [" + groupTag + "] was not found in message");
}
return groups;
}
@Override
public <T, C extends Collection<T>> C getGroups(Message fixMessage,
Class<C> type,
int groupTag,
FixBlockMeta<T> componentMeta,
boolean optional) {
C groups = getGroupsFromMap(fixMessage, type, groupTag, componentMeta);
if (groups.isEmpty()) {
groups = getGroupsFromMap(fixMessage.getHeader(), type, groupTag, componentMeta);
}
if (!optional && groups.isEmpty()) {
throw new FixException("Group [" + groupTag + "] was not found in message");
}
return groups;
}
@SuppressWarnings("unchecked")
private <T, C extends Collection<T>> C getGroupsFromMap(FieldMap fieldMap,
Class<C> type,
int tag,
FixBlockMeta<T> componentMeta) {
try {
|
final C result = CollectionFactory.createCollection(type);
|
YTEQ/fixb
|
fixb-quickfix/src/main/java/org/fixb/quickfix/FixMetaDataDictionary.java
|
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
|
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import com.google.common.collect.ImmutableMap;
import org.fixb.meta.*;
import quickfix.ConfigError;
import quickfix.DataDictionary;
import quickfix.FixVersions;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
|
} catch (XMLStreamException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(stream.toString().getBytes());
}
private static void addStandardHeaderAndTrailerFields(final Map<FixFieldMeta, String> fields,
final Map<Integer, String> fieldNames) throws XMLStreamException {
for (Map.Entry<Integer, String> field : HEADER_FIELDS.entrySet()) {
fields.put(new FixConstantFieldMeta(field.getKey(), true, ""), field.getValue());
fieldNames.put(field.getKey(), field.getValue());
}
for (Map.Entry<Integer, String> field : TRAILER_FIELDS.entrySet()) {
fields.put(new FixConstantFieldMeta(field.getKey(), true, ""), field.getValue());
fieldNames.put(field.getKey(), field.getValue());
}
}
private static void writeHeader(final XMLStreamWriter writer, final String fixProtocolVersion, FixMetaDictionary fixMetaDictionary) throws XMLStreamException {
if (isLessThan50Version(fixProtocolVersion)) {
writer.writeStartElement(HEADER);
for (Map.Entry<Integer, String> field : HEADER_FIELDS.entrySet()) {
writer.writeStartElement(FIELD);
writer.writeAttribute(NAME, field.getValue());
writer.writeAttribute(REQUIRED, YES);
writer.writeEndElement();
}
for (FixMessageMeta<?> message : fixMetaDictionary.getAllMessageMetas()) {
for (FixFieldMeta field : message.getFields()) {
|
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
// Path: fixb-quickfix/src/main/java/org/fixb/quickfix/FixMetaDataDictionary.java
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import com.google.common.collect.ImmutableMap;
import org.fixb.meta.*;
import quickfix.ConfigError;
import quickfix.DataDictionary;
import quickfix.FixVersions;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
} catch (XMLStreamException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(stream.toString().getBytes());
}
private static void addStandardHeaderAndTrailerFields(final Map<FixFieldMeta, String> fields,
final Map<Integer, String> fieldNames) throws XMLStreamException {
for (Map.Entry<Integer, String> field : HEADER_FIELDS.entrySet()) {
fields.put(new FixConstantFieldMeta(field.getKey(), true, ""), field.getValue());
fieldNames.put(field.getKey(), field.getValue());
}
for (Map.Entry<Integer, String> field : TRAILER_FIELDS.entrySet()) {
fields.put(new FixConstantFieldMeta(field.getKey(), true, ""), field.getValue());
fieldNames.put(field.getKey(), field.getValue());
}
}
private static void writeHeader(final XMLStreamWriter writer, final String fixProtocolVersion, FixMetaDictionary fixMetaDictionary) throws XMLStreamException {
if (isLessThan50Version(fixProtocolVersion)) {
writer.writeStartElement(HEADER);
for (Map.Entry<Integer, String> field : HEADER_FIELDS.entrySet()) {
writer.writeStartElement(FIELD);
writer.writeAttribute(NAME, field.getValue());
writer.writeAttribute(REQUIRED, YES);
writer.writeEndElement();
}
for (FixMessageMeta<?> message : fixMetaDictionary.getAllMessageMetas()) {
for (FixFieldMeta field : message.getFields()) {
|
if (field.isHeader() && field.getTag() != MSG_TYPE_TAG) {
|
YTEQ/fixb
|
fixb-quickfix/src/main/java/org/fixb/quickfix/FixMetaDataDictionary.java
|
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
|
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import com.google.common.collect.ImmutableMap;
import org.fixb.meta.*;
import quickfix.ConfigError;
import quickfix.DataDictionary;
import quickfix.FixVersions;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
|
}
private static void writeFixPreambule(final XMLStreamWriter writer,
final String fixProtocolVersion) throws XMLStreamException {
final String[] tokens = fixProtocolVersion.split("\\.");
if (tokens.length < 3) {
throw new RuntimeException("Invalid FIX version: " + fixProtocolVersion);
}
writer.writeAttribute(PREAMBULE_TYPE, tokens[0]);
writer.writeAttribute(VERSION_MAJOR, tokens[1]);
writer.writeAttribute(VERSION_MINOR, tokens[2]);
}
private static void writeMessageXml(final XMLStreamWriter writer,
final FixMessageMeta<?> message,
final Map<FixFieldMeta, String> fields,
final Map<Integer, String> fieldNames) throws XMLStreamException {
writer.writeStartElement(MESSAGE);
writer.writeAttribute(NAME, message.getType().getSimpleName());
writer.writeAttribute(MSGTYPE, message.getMessageType());
writer.writeAttribute(MSGCAT, MSGCAT_APP);
writeComponentFields(writer, message, fields, fieldNames);
writer.writeEndElement();
}
private static void writeComponentFields(final XMLStreamWriter writer,
final FixBlockMeta<?> message,
final Map<FixFieldMeta, String> fields,
final Map<Integer, String> fieldNames) throws XMLStreamException {
for (FixFieldMeta field : message.getFields()) {
|
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int MSG_TYPE_TAG = 35;
// Path: fixb-quickfix/src/main/java/org/fixb/quickfix/FixMetaDataDictionary.java
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.FixConstants.MSG_TYPE_TAG;
import com.google.common.collect.ImmutableMap;
import org.fixb.meta.*;
import quickfix.ConfigError;
import quickfix.DataDictionary;
import quickfix.FixVersions;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
}
private static void writeFixPreambule(final XMLStreamWriter writer,
final String fixProtocolVersion) throws XMLStreamException {
final String[] tokens = fixProtocolVersion.split("\\.");
if (tokens.length < 3) {
throw new RuntimeException("Invalid FIX version: " + fixProtocolVersion);
}
writer.writeAttribute(PREAMBULE_TYPE, tokens[0]);
writer.writeAttribute(VERSION_MAJOR, tokens[1]);
writer.writeAttribute(VERSION_MINOR, tokens[2]);
}
private static void writeMessageXml(final XMLStreamWriter writer,
final FixMessageMeta<?> message,
final Map<FixFieldMeta, String> fields,
final Map<Integer, String> fieldNames) throws XMLStreamException {
writer.writeStartElement(MESSAGE);
writer.writeAttribute(NAME, message.getType().getSimpleName());
writer.writeAttribute(MSGTYPE, message.getMessageType());
writer.writeAttribute(MSGCAT, MSGCAT_APP);
writeComponentFields(writer, message, fields, fieldNames);
writer.writeEndElement();
}
private static void writeComponentFields(final XMLStreamWriter writer,
final FixBlockMeta<?> message,
final Map<FixFieldMeta, String> fields,
final Map<Integer, String> fieldNames) throws XMLStreamException {
for (FixFieldMeta field : message.getFields()) {
|
if (MSG_TYPE_TAG != field.getTag() && BEGIN_STRING_TAG != field.getTag()) {
|
YTEQ/fixb
|
fixb/src/main/java/org/fixb/meta/FixBlockMeta.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
|
import com.google.common.base.Optional;
import org.fixb.FixException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.*;
import static java.util.Collections.unmodifiableList;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.meta;
/**
* A FIX block metadata (a set of FIX fields and repeating groups), e.g. CParty.
*
* @param <T>
* @author vladyslav.yatsenko
*/
public class FixBlockMeta<T> {
private final Class<T> type;
private final Optional<Constructor<T>> constructor;
private final List<FixFieldMeta> fields;
/**
* The same as FixBlockMeta, but with useConstructor default to false.
*
* @param type the domain object type this FixBlockMeta is for
* @param fields the fields metadata
*/
public FixBlockMeta(Class<T> type, List<? extends FixFieldMeta> fields) {
this(type, fields, false);
}
/**
* @param type the domain object type this FixBlockMeta is for
* @param fields the fields metadata
* @param useConstructor identifies whether to use constructor for instance initialisations
*/
@SuppressWarnings("unchecked")
public FixBlockMeta(Class<T> type, List<? extends FixFieldMeta> fields, boolean useConstructor) {
this.type = type;
this.constructor = useConstructor ? Optional.of((Constructor<T>) type.getConstructors()[0]) : Optional.<Constructor<T>>absent();
this.fields = unmodifiableList(fields);
}
/**
* @return the related domain object type.
*/
public Class<T> getType() {
return type;
}
/**
* @return the fields metadata.
*/
public List<FixFieldMeta> getFields() {
return fields;
}
/**
* @param values constructor parameter values
* @return a domain object created using given parameter values.
*/
public T createModel(Map<FixFieldMeta, Object> values) {
try {
return (constructor.isPresent()) ?
createModel(constructor.get(), values, 0) :
createModel(type, values, 0);
} catch (Exception e) {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
// Path: fixb/src/main/java/org/fixb/meta/FixBlockMeta.java
import com.google.common.base.Optional;
import org.fixb.FixException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.*;
import static java.util.Collections.unmodifiableList;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.meta;
/**
* A FIX block metadata (a set of FIX fields and repeating groups), e.g. CParty.
*
* @param <T>
* @author vladyslav.yatsenko
*/
public class FixBlockMeta<T> {
private final Class<T> type;
private final Optional<Constructor<T>> constructor;
private final List<FixFieldMeta> fields;
/**
* The same as FixBlockMeta, but with useConstructor default to false.
*
* @param type the domain object type this FixBlockMeta is for
* @param fields the fields metadata
*/
public FixBlockMeta(Class<T> type, List<? extends FixFieldMeta> fields) {
this(type, fields, false);
}
/**
* @param type the domain object type this FixBlockMeta is for
* @param fields the fields metadata
* @param useConstructor identifies whether to use constructor for instance initialisations
*/
@SuppressWarnings("unchecked")
public FixBlockMeta(Class<T> type, List<? extends FixFieldMeta> fields, boolean useConstructor) {
this.type = type;
this.constructor = useConstructor ? Optional.of((Constructor<T>) type.getConstructors()[0]) : Optional.<Constructor<T>>absent();
this.fields = unmodifiableList(fields);
}
/**
* @return the related domain object type.
*/
public Class<T> getType() {
return type;
}
/**
* @return the fields metadata.
*/
public List<FixFieldMeta> getFields() {
return fields;
}
/**
* @param values constructor parameter values
* @return a domain object created using given parameter values.
*/
public T createModel(Map<FixFieldMeta, Object> values) {
try {
return (constructor.isPresent()) ?
createModel(constructor.get(), values, 0) :
createModel(type, values, 0);
} catch (Exception e) {
|
throw new FixException("Unable to create object from FIX parameters: " + values.values(), e);
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
|
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
*/
public class NativeFixMessageBuilderTest {
private final FixEnumDictionary fixEnumDictionary = mock(FixEnumDictionary.class);
private final NativeFixMessageBuilder builder = new NativeFixMessageBuilder.Factory(fixEnumDictionary).create();
{
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
// Path: fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
*/
public class NativeFixMessageBuilderTest {
private final FixEnumDictionary fixEnumDictionary = mock(FixEnumDictionary.class);
private final NativeFixMessageBuilder builder = new NativeFixMessageBuilder.Factory(fixEnumDictionary).create();
{
|
when(fixEnumDictionary.getFixEnumMeta(Side.class)).thenReturn(FixEnumMeta.forClass(Side.class));
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
|
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
*/
public class NativeFixMessageBuilderTest {
private final FixEnumDictionary fixEnumDictionary = mock(FixEnumDictionary.class);
private final NativeFixMessageBuilder builder = new NativeFixMessageBuilder.Factory(fixEnumDictionary).create();
{
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
// Path: fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
*/
public class NativeFixMessageBuilderTest {
private final FixEnumDictionary fixEnumDictionary = mock(FixEnumDictionary.class);
private final NativeFixMessageBuilder builder = new NativeFixMessageBuilder.Factory(fixEnumDictionary).create();
{
|
when(fixEnumDictionary.getFixEnumMeta(Side.class)).thenReturn(FixEnumMeta.forClass(Side.class));
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
|
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
*/
public class NativeFixMessageBuilderTest {
private final FixEnumDictionary fixEnumDictionary = mock(FixEnumDictionary.class);
private final NativeFixMessageBuilder builder = new NativeFixMessageBuilder.Factory(fixEnumDictionary).create();
{
when(fixEnumDictionary.getFixEnumMeta(Side.class)).thenReturn(FixEnumMeta.forClass(Side.class));
}
@Test
public void testBuild() throws Exception {
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
// Path: fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
*/
public class NativeFixMessageBuilderTest {
private final FixEnumDictionary fixEnumDictionary = mock(FixEnumDictionary.class);
private final NativeFixMessageBuilder builder = new NativeFixMessageBuilder.Factory(fixEnumDictionary).create();
{
when(fixEnumDictionary.getFixEnumMeta(Side.class)).thenReturn(FixEnumMeta.forClass(Side.class));
}
@Test
public void testBuild() throws Exception {
|
builder.setField(BEGIN_STRING_TAG, "FIX.5.0");
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
|
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
|
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
*/
public class NativeFixMessageBuilderTest {
private final FixEnumDictionary fixEnumDictionary = mock(FixEnumDictionary.class);
private final NativeFixMessageBuilder builder = new NativeFixMessageBuilder.Factory(fixEnumDictionary).create();
{
when(fixEnumDictionary.getFixEnumMeta(Side.class)).thenReturn(FixEnumMeta.forClass(Side.class));
}
@Test
public void testBuild() throws Exception {
builder.setField(BEGIN_STRING_TAG, "FIX.5.0");
builder.setField(11, 'a');
builder.setField(12, 1);
builder.setField(13, 11.00);
builder.setField(14, true);
builder.setField(15, new BigDecimal("1.23"));
builder.setField(16, "string");
builder.setField(17, new LocalDate("2012-02-01").toDateMidnight().toDate());
builder.setField(18, Side.SELL);
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
// Path: fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
/*
* Copyright 2013 YTEQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fixb.impl;
/**
*/
public class NativeFixMessageBuilderTest {
private final FixEnumDictionary fixEnumDictionary = mock(FixEnumDictionary.class);
private final NativeFixMessageBuilder builder = new NativeFixMessageBuilder.Factory(fixEnumDictionary).create();
{
when(fixEnumDictionary.getFixEnumMeta(Side.class)).thenReturn(FixEnumMeta.forClass(Side.class));
}
@Test
public void testBuild() throws Exception {
builder.setField(BEGIN_STRING_TAG, "FIX.5.0");
builder.setField(11, 'a');
builder.setField(12, 1);
builder.setField(13, 11.00);
builder.setField(14, true);
builder.setField(15, new BigDecimal("1.23"));
builder.setField(16, "string");
builder.setField(17, new LocalDate("2012-02-01").toDateMidnight().toDate());
builder.setField(18, Side.SELL);
|
final String fix = builder.build();
|
YTEQ/fixb
|
fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
|
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
|
"12=1",
"13=11.0",
"14=Y",
"15=1.23",
"16=string",
"17=20120201-00:00:00",
"18=1",
"10=[0-9]+")));
}
@Test
public void testBuildWithJodaTime() throws Exception {
builder.setField(BEGIN_STRING_TAG, "FIX.5.0");
builder.setField(11, new LocalDate("2012-02-01"));
builder.setField(12, new LocalTime("15:15:15.123"));
builder.setField(13, new LocalDateTime("2012-02-01"));
builder.setField(14, new DateTime("2012-02-01T01:00:00", DateTimeZone.forOffsetHours(2)));
final String fix = builder.build();
assertTrue("Fix message is incorrect", fix.matches(fix(
"8=FIX.5.0",
"9=75",
"11=20120201",
"12=15:15:15.123",
"13=20120201-00:00:00",
"14=20120201-01:00:00\\+0200",
"10=[0-9]+")));
}
|
// Path: fixb/src/main/java/org/fixb/FixException.java
// public class FixException extends RuntimeException {
// private static final long serialVersionUID = 1;
//
// /**
// * @param tag the field tag that has not been found
// * @param fixMessage the FIX message that does not contain the tag
// * @return an instance of FixException for a field-not-found case.
// */
// public static FixException fieldNotFound(int tag, String fixMessage) {
// return new FixException("Field [" + tag + "] was not found in message: " + fixMessage);
// }
//
// /**
// * @param message the exception message
// * @param cause the exception cause
// */
// public FixException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @param cause the exception cause
// */
// public FixException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// /**
// * @param message the exception message
// */
// public FixException(final String message) {
// super(message);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumMeta.java
// public class FixEnumMeta<T extends Enum<T>> {
// private final Class<T> enumClass;
// private final BiMap<String, T> enumFixValues;
//
// public static <T extends Enum<T>> FixEnumMeta<T> forClass(Class<T> type) {
// if (!type.isEnum()) {
// throw new FixException("Expected an enum class, but got [" + type.getName() + "].");
// }
// return new FixEnumMeta<>(type);
// }
//
// private FixEnumMeta(Class<T> enumType) {
// try {
// final ImmutableBiMap.Builder<String, T> mapBuilder = ImmutableBiMap.builder();
//
// for (Field field : enumType.getFields()) {
// if (field.isEnumConstant()) {
// FixValue fixValue = field.getAnnotation(FixValue.class);
// if (fixValue == null) {
// throw new FixException("Not all enum values of [" + enumType.getName() + "] have @FixValue annotation: " + field.get(null));
// }
// mapBuilder.put(fixValue.value(), (T) field.get(null));
// }
// }
//
// this.enumClass = enumType;
// this.enumFixValues = mapBuilder.build();
//
// } catch (IllegalAccessException e) {
// throw new FixException("Invalid FIX enum mapping", e);
// }
// }
//
// public Class<T> getType() {
// return enumClass;
// }
//
// public Enum<T> enumForFixValue(String fixValue) {
// return enumFixValues.get(fixValue);
// }
//
// public String fixValueForEnum(Enum<?> enumValue) {
// return enumFixValues.inverse().get(enumValue);
// }
// }
//
// Path: fixb/src/main/java/org/fixb/meta/FixEnumDictionary.java
// public interface FixEnumDictionary {
// /**
// * @param enumType the enum type
// * @param <T> the enum type
// * @return FIX enum value bindings for the given enum type.
// */
// <T extends Enum<T>> FixEnumMeta<T> getFixEnumMeta(Class<T> enumType);
//
// /**
// * @param enumType the enum type
// * @return true if there is a meta object for the given enum class in this dictionary, false otherwise.
// */
// boolean hasFixEnumMeta(Class<?> enumType);
// }
//
// Path: fixb/src/main/java/org/fixb/FixConstants.java
// public static final int BEGIN_STRING_TAG = 8;
//
// Path: fixb/src/test/java/org/fixb/test/TestHelper.java
// public static String fix(String... fields) {
// StringBuilder result = new StringBuilder();
// for (String field : fields) {
// if (result.length() > 0) result.append(SOH);
// result.append(field);
// }
//
// return result.toString();
// }
//
// Path: fixb/src/test/java/org/fixb/test/data/SampleQuote.java
// @FixEnum
// public static enum Side {
// @FixValue("0") BUY,
// @FixValue("1") SELL;
// }
// Path: fixb/src/test/java/org/fixb/impl/NativeFixMessageBuilderTest.java
import static org.mockito.Mockito.when;
import org.fixb.FixException;
import org.fixb.meta.FixEnumMeta;
import org.fixb.meta.FixEnumDictionary;
import org.joda.time.*;
import org.junit.Test;
import java.math.BigDecimal;
import static org.fixb.FixConstants.BEGIN_STRING_TAG;
import static org.fixb.test.TestHelper.fix;
import static org.fixb.test.data.SampleQuote.Side;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
"12=1",
"13=11.0",
"14=Y",
"15=1.23",
"16=string",
"17=20120201-00:00:00",
"18=1",
"10=[0-9]+")));
}
@Test
public void testBuildWithJodaTime() throws Exception {
builder.setField(BEGIN_STRING_TAG, "FIX.5.0");
builder.setField(11, new LocalDate("2012-02-01"));
builder.setField(12, new LocalTime("15:15:15.123"));
builder.setField(13, new LocalDateTime("2012-02-01"));
builder.setField(14, new DateTime("2012-02-01T01:00:00", DateTimeZone.forOffsetHours(2)));
final String fix = builder.build();
assertTrue("Fix message is incorrect", fix.matches(fix(
"8=FIX.5.0",
"9=75",
"11=20120201",
"12=15:15:15.123",
"13=20120201-00:00:00",
"14=20120201-01:00:00\\+0200",
"10=[0-9]+")));
}
|
@Test(expected = FixException.class)
|
jajja/jorm
|
src/main/java/com/jajja/jorm/Composite.java
|
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class Field {
// private Object value = null;
// private boolean isChanged = false;
//
// Field() {}
//
// public Field(Object value) {
// setValue(value);
// setChanged(true);
// }
//
// void setValue(Object value) {
// this.value = value;
// }
//
// public <T> T value(Class<T> type) {
// return convert(value, type);
// }
//
// public Object rawValue() {
// return value;
// }
//
// public Record record() {
// return (value instanceof Record) ? ((Record)value) : null;
// }
//
// // @SuppressWarnings("unchecked")
// // public <T extends Record> T ref(Transaction t, Class<T> clazz) throws SQLException {
// // if (record() == null) {
// // if (isReferenceCacheOnly) {
// // return null;
// // }
// // if (!flag(FLAG_REF_FETCH)) {
// // throw new IllegalAccessError("Reference fetching is disabled");
// // }
// // setValue(t.findById((Class<? extends Record>)clazz, value));
// // }
// // return (T)record();
// // }
//
// public Object dereference() {
// return (value instanceof Record) ? ((Record)value).id() : value;
// }
//
// void setChanged(boolean isChanged) {
// this.isChanged = isChanged;
// }
//
// public boolean isChanged() {
// return isChanged;
// }
//
// @Override
// public String toString() {
// return String.format("Field [value => %s, isChanged => %s]", value, isChanged);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Field) {
// Object v = ((Field)obj).value;
// return (value == v || (value != null && value.equals(v)));
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// return (value != null) ? value.hashCode() : 0;
// }
// }
|
import com.jajja.jorm.Row.Field;
|
/*
* Copyright (C) 2014 Jajja Communications AB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jajja.jorm;
public class Composite {
private final String[] columns;
private int hashCode = 0;
private boolean hashCodeSet = false;
public Composite(String ... columns) {
this.columns = StringPool.array(columns);
}
public static Composite get(Object o) {
if (o instanceof String) {
return new Composite((String)o);
} else if (o instanceof Composite) {
return (Composite)o;
}
throw new IllegalArgumentException();
}
public Value valueFrom(Row row) {
Object[] values = new Object[columns.length];
for (int i = 0; i < columns.length; i++) {
values[i] = row.get(columns[i]);
}
return new Value(this, values);
}
public Value valueFrom(Row row, boolean noRefresh) {
if (!noRefresh) {
return valueFrom(row);
}
Object[] values = new Object[columns.length];
for (int i = 0; i < columns.length; i++) {
|
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class Field {
// private Object value = null;
// private boolean isChanged = false;
//
// Field() {}
//
// public Field(Object value) {
// setValue(value);
// setChanged(true);
// }
//
// void setValue(Object value) {
// this.value = value;
// }
//
// public <T> T value(Class<T> type) {
// return convert(value, type);
// }
//
// public Object rawValue() {
// return value;
// }
//
// public Record record() {
// return (value instanceof Record) ? ((Record)value) : null;
// }
//
// // @SuppressWarnings("unchecked")
// // public <T extends Record> T ref(Transaction t, Class<T> clazz) throws SQLException {
// // if (record() == null) {
// // if (isReferenceCacheOnly) {
// // return null;
// // }
// // if (!flag(FLAG_REF_FETCH)) {
// // throw new IllegalAccessError("Reference fetching is disabled");
// // }
// // setValue(t.findById((Class<? extends Record>)clazz, value));
// // }
// // return (T)record();
// // }
//
// public Object dereference() {
// return (value instanceof Record) ? ((Record)value).id() : value;
// }
//
// void setChanged(boolean isChanged) {
// this.isChanged = isChanged;
// }
//
// public boolean isChanged() {
// return isChanged;
// }
//
// @Override
// public String toString() {
// return String.format("Field [value => %s, isChanged => %s]", value, isChanged);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Field) {
// Object v = ((Field)obj).value;
// return (value == v || (value != null && value.equals(v)));
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// return (value != null) ? value.hashCode() : 0;
// }
// }
// Path: src/main/java/com/jajja/jorm/Composite.java
import com.jajja.jorm.Row.Field;
/*
* Copyright (C) 2014 Jajja Communications AB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jajja.jorm;
public class Composite {
private final String[] columns;
private int hashCode = 0;
private boolean hashCodeSet = false;
public Composite(String ... columns) {
this.columns = StringPool.array(columns);
}
public static Composite get(Object o) {
if (o instanceof String) {
return new Composite((String)o);
} else if (o instanceof Composite) {
return (Composite)o;
}
throw new IllegalArgumentException();
}
public Value valueFrom(Row row) {
Object[] values = new Object[columns.length];
for (int i = 0; i < columns.length; i++) {
values[i] = row.get(columns[i]);
}
return new Value(this, values);
}
public Value valueFrom(Row row, boolean noRefresh) {
if (!noRefresh) {
return valueFrom(row);
}
Object[] values = new Object[columns.length];
for (int i = 0; i < columns.length; i++) {
|
Field field = row.field(columns[i]);
|
jajja/jorm
|
src/main/java/com/jajja/jorm/patch/Patcher.java
|
// Path: src/main/java/com/jajja/jorm/patch/postgres/FixedPGmoney.java
// @SuppressWarnings("serial")
// public class FixedPGmoney extends org.postgresql.util.PGmoney {
// public FixedPGmoney() {
// super();
// }
//
// public FixedPGmoney(org.postgresql.util.PGmoney o) {
// super();
// setType(o.getType());
// try {
// setValue(o.getValue());
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// val = o.val;
// }
//
// @Override
// public int hashCode() {
// return getType().hashCode() + getValue().hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FixedPGmoney) {
// return ((FixedPGmoney)obj).getValue().equals(getValue()) && ((FixedPGmoney)obj).getType().equals(getType());
// }
// return false;
// }
// }
//
// Path: src/main/java/com/jajja/jorm/patch/postgres/FixedPGobject.java
// @SuppressWarnings("serial")
// public class FixedPGobject extends org.postgresql.util.PGobject {
// public FixedPGobject() {
// super();
// }
//
// public FixedPGobject(org.postgresql.util.PGobject o) {
// super();
// setType(o.getType());
// try {
// setValue(o.getValue());
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int hashCode() {
// return getType().hashCode() + getValue().hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FixedPGobject) {
// return ((FixedPGobject)obj).getValue().equals(getValue()) && ((FixedPGobject)obj).getType().equals(getType());
// }
// return false;
// }
// }
|
import java.util.HashMap;
import org.postgresql.util.PGmoney;
import org.postgresql.util.PGobject;
import com.jajja.jorm.patch.postgres.FixedPGmoney;
import com.jajja.jorm.patch.postgres.FixedPGobject;
|
public static class NoopFulpatcher extends Patcher {
private NoopFulpatcher() {
}
@Override
protected Object debork(Object v) {
return v;
}
}
private static class PGobjectFulpatcher extends Patcher {
private PGobjectFulpatcher() throws Exception {
PGobject a = new PGobject();
PGobject b = new PGobject();
a.setType("a");
b.setType("b");
a.setValue("test");
b.setValue("test");
if (a.equals(b)) { // should not equal; type differs
return;
}
b.setType("a");
if (a.hashCode() != b.hashCode()) {
return;
}
}
@Override
protected Object debork(Object v) {
|
// Path: src/main/java/com/jajja/jorm/patch/postgres/FixedPGmoney.java
// @SuppressWarnings("serial")
// public class FixedPGmoney extends org.postgresql.util.PGmoney {
// public FixedPGmoney() {
// super();
// }
//
// public FixedPGmoney(org.postgresql.util.PGmoney o) {
// super();
// setType(o.getType());
// try {
// setValue(o.getValue());
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// val = o.val;
// }
//
// @Override
// public int hashCode() {
// return getType().hashCode() + getValue().hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FixedPGmoney) {
// return ((FixedPGmoney)obj).getValue().equals(getValue()) && ((FixedPGmoney)obj).getType().equals(getType());
// }
// return false;
// }
// }
//
// Path: src/main/java/com/jajja/jorm/patch/postgres/FixedPGobject.java
// @SuppressWarnings("serial")
// public class FixedPGobject extends org.postgresql.util.PGobject {
// public FixedPGobject() {
// super();
// }
//
// public FixedPGobject(org.postgresql.util.PGobject o) {
// super();
// setType(o.getType());
// try {
// setValue(o.getValue());
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int hashCode() {
// return getType().hashCode() + getValue().hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FixedPGobject) {
// return ((FixedPGobject)obj).getValue().equals(getValue()) && ((FixedPGobject)obj).getType().equals(getType());
// }
// return false;
// }
// }
// Path: src/main/java/com/jajja/jorm/patch/Patcher.java
import java.util.HashMap;
import org.postgresql.util.PGmoney;
import org.postgresql.util.PGobject;
import com.jajja.jorm.patch.postgres.FixedPGmoney;
import com.jajja.jorm.patch.postgres.FixedPGobject;
public static class NoopFulpatcher extends Patcher {
private NoopFulpatcher() {
}
@Override
protected Object debork(Object v) {
return v;
}
}
private static class PGobjectFulpatcher extends Patcher {
private PGobjectFulpatcher() throws Exception {
PGobject a = new PGobject();
PGobject b = new PGobject();
a.setType("a");
b.setType("b");
a.setValue("test");
b.setValue("test");
if (a.equals(b)) { // should not equal; type differs
return;
}
b.setType("a");
if (a.hashCode() != b.hashCode()) {
return;
}
}
@Override
protected Object debork(Object v) {
|
return new FixedPGobject((PGobject)v);
|
jajja/jorm
|
src/main/java/com/jajja/jorm/patch/Patcher.java
|
// Path: src/main/java/com/jajja/jorm/patch/postgres/FixedPGmoney.java
// @SuppressWarnings("serial")
// public class FixedPGmoney extends org.postgresql.util.PGmoney {
// public FixedPGmoney() {
// super();
// }
//
// public FixedPGmoney(org.postgresql.util.PGmoney o) {
// super();
// setType(o.getType());
// try {
// setValue(o.getValue());
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// val = o.val;
// }
//
// @Override
// public int hashCode() {
// return getType().hashCode() + getValue().hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FixedPGmoney) {
// return ((FixedPGmoney)obj).getValue().equals(getValue()) && ((FixedPGmoney)obj).getType().equals(getType());
// }
// return false;
// }
// }
//
// Path: src/main/java/com/jajja/jorm/patch/postgres/FixedPGobject.java
// @SuppressWarnings("serial")
// public class FixedPGobject extends org.postgresql.util.PGobject {
// public FixedPGobject() {
// super();
// }
//
// public FixedPGobject(org.postgresql.util.PGobject o) {
// super();
// setType(o.getType());
// try {
// setValue(o.getValue());
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int hashCode() {
// return getType().hashCode() + getValue().hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FixedPGobject) {
// return ((FixedPGobject)obj).getValue().equals(getValue()) && ((FixedPGobject)obj).getType().equals(getType());
// }
// return false;
// }
// }
|
import java.util.HashMap;
import org.postgresql.util.PGmoney;
import org.postgresql.util.PGobject;
import com.jajja.jorm.patch.postgres.FixedPGmoney;
import com.jajja.jorm.patch.postgres.FixedPGobject;
|
a.setType("a");
b.setType("b");
a.setValue("test");
b.setValue("test");
if (a.equals(b)) { // should not equal; type differs
return;
}
b.setType("a");
if (a.hashCode() != b.hashCode()) {
return;
}
}
@Override
protected Object debork(Object v) {
return new FixedPGobject((PGobject)v);
}
}
private static class PGmoneyFulpatcher extends Patcher {
private PGmoneyFulpatcher() throws Exception {
PGmoney a = new PGmoney(12.34);
PGmoney b = new PGmoney(12.34);
if (a.hashCode() != b.hashCode()) {
throw new Exception("bugged");
}
}
@Override
protected Object debork(Object v) {
|
// Path: src/main/java/com/jajja/jorm/patch/postgres/FixedPGmoney.java
// @SuppressWarnings("serial")
// public class FixedPGmoney extends org.postgresql.util.PGmoney {
// public FixedPGmoney() {
// super();
// }
//
// public FixedPGmoney(org.postgresql.util.PGmoney o) {
// super();
// setType(o.getType());
// try {
// setValue(o.getValue());
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// val = o.val;
// }
//
// @Override
// public int hashCode() {
// return getType().hashCode() + getValue().hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FixedPGmoney) {
// return ((FixedPGmoney)obj).getValue().equals(getValue()) && ((FixedPGmoney)obj).getType().equals(getType());
// }
// return false;
// }
// }
//
// Path: src/main/java/com/jajja/jorm/patch/postgres/FixedPGobject.java
// @SuppressWarnings("serial")
// public class FixedPGobject extends org.postgresql.util.PGobject {
// public FixedPGobject() {
// super();
// }
//
// public FixedPGobject(org.postgresql.util.PGobject o) {
// super();
// setType(o.getType());
// try {
// setValue(o.getValue());
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int hashCode() {
// return getType().hashCode() + getValue().hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FixedPGobject) {
// return ((FixedPGobject)obj).getValue().equals(getValue()) && ((FixedPGobject)obj).getType().equals(getType());
// }
// return false;
// }
// }
// Path: src/main/java/com/jajja/jorm/patch/Patcher.java
import java.util.HashMap;
import org.postgresql.util.PGmoney;
import org.postgresql.util.PGobject;
import com.jajja.jorm.patch.postgres.FixedPGmoney;
import com.jajja.jorm.patch.postgres.FixedPGobject;
a.setType("a");
b.setType("b");
a.setValue("test");
b.setValue("test");
if (a.equals(b)) { // should not equal; type differs
return;
}
b.setType("a");
if (a.hashCode() != b.hashCode()) {
return;
}
}
@Override
protected Object debork(Object v) {
return new FixedPGobject((PGobject)v);
}
}
private static class PGmoneyFulpatcher extends Patcher {
private PGmoneyFulpatcher() throws Exception {
PGmoney a = new PGmoney(12.34);
PGmoney b = new PGmoney(12.34);
if (a.hashCode() != b.hashCode()) {
throw new Exception("bugged");
}
}
@Override
protected Object debork(Object v) {
|
return new FixedPGmoney((PGmoney)v);
|
jajja/jorm
|
src/main/java/com/jajja/jorm/Row.java
|
// Path: src/main/java/com/jajja/jorm/Composite.java
// public static class Value {
// private Composite composite;
// private Object[] values;
//
// private Value(Composite composite, Object ... values) {
// this.composite = composite;
// this.values = values;
// }
//
// public Composite getComposite() {
// return composite;
// }
//
// public Object[] getValues() {
// return values;
// }
//
// public Object getValue() {
// if (!isSingle()) {
// throw new RuntimeException("Not a single column key");
// }
// return values[0];
// }
//
// private int getOffset(String column) {
// for (int i = 0; i < composite.columns.length; i++) {
// if (composite.columns[i].equals(column)) {
// return i;
// }
// }
// return -1;
// }
//
// @SuppressWarnings("unchecked")
// public <T> T get(String column, Class<T> clazz) {
// int offset = getOffset(column);
// if (offset < 0) {
// throw new IllegalArgumentException("No such column " + column);
// }
// Object value = values[offset];
// if (value == null) {
// return null;
// }
// return (T)value;
// }
//
// public boolean isSingle() {
// return values.length == 1;
// }
//
// @Override
// public int hashCode() {
// int hashCode = 0;
// for (Object value : values) {
// if (value != null) {
// hashCode += value.hashCode();
// }
// }
// return hashCode;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Value) {
// Value v = (Value)obj;
// if (values.length != v.values.length) {
// return false;
// }
// for (int i = 0; i < values.length; i++) {
// if (!((values[i] == v.values[i]) || (values[i] != null && values[i].equals(v.values[i])))) {
// return false;
// }
// }
// return true;
// }
// return false;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder(16 * values.length);
// sb.append("{");
// boolean isFirst = true;
// for (Object value : values) {
// if (!isFirst) {
// sb.append(", ");
// } else {
// isFirst = false;
// }
// sb.append(value);
// }
// sb.append("}");
// return sb.toString();
// }
// }
|
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.jajja.jorm.Composite.Value;
|
flag(FLAG_REF_FETCH, false);
}
void put(String column, Object value) {
Field field = field(column);
if (field == null) {
field = new Field();
column = StringPool.get(column);
}
field.setChanged(true);
field.setValue(value);
fields.put(column, field);
}
/**
* Sets the specified column to value.
*
* If the value refers to a {@link Record} it is stored as a reference,
* and the column is assigned the value of the Record's primary key.
*
* @param column the column name
* @param value the value
*/
public void set(String column, Object value) {
assertNotReadOnly();
put(column, value);
}
|
// Path: src/main/java/com/jajja/jorm/Composite.java
// public static class Value {
// private Composite composite;
// private Object[] values;
//
// private Value(Composite composite, Object ... values) {
// this.composite = composite;
// this.values = values;
// }
//
// public Composite getComposite() {
// return composite;
// }
//
// public Object[] getValues() {
// return values;
// }
//
// public Object getValue() {
// if (!isSingle()) {
// throw new RuntimeException("Not a single column key");
// }
// return values[0];
// }
//
// private int getOffset(String column) {
// for (int i = 0; i < composite.columns.length; i++) {
// if (composite.columns[i].equals(column)) {
// return i;
// }
// }
// return -1;
// }
//
// @SuppressWarnings("unchecked")
// public <T> T get(String column, Class<T> clazz) {
// int offset = getOffset(column);
// if (offset < 0) {
// throw new IllegalArgumentException("No such column " + column);
// }
// Object value = values[offset];
// if (value == null) {
// return null;
// }
// return (T)value;
// }
//
// public boolean isSingle() {
// return values.length == 1;
// }
//
// @Override
// public int hashCode() {
// int hashCode = 0;
// for (Object value : values) {
// if (value != null) {
// hashCode += value.hashCode();
// }
// }
// return hashCode;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Value) {
// Value v = (Value)obj;
// if (values.length != v.values.length) {
// return false;
// }
// for (int i = 0; i < values.length; i++) {
// if (!((values[i] == v.values[i]) || (values[i] != null && values[i].equals(v.values[i])))) {
// return false;
// }
// }
// return true;
// }
// return false;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder(16 * values.length);
// sb.append("{");
// boolean isFirst = true;
// for (Object value : values) {
// if (!isFirst) {
// sb.append(", ");
// } else {
// isFirst = false;
// }
// sb.append(value);
// }
// sb.append("}");
// return sb.toString();
// }
// }
// Path: src/main/java/com/jajja/jorm/Row.java
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.jajja.jorm.Composite.Value;
flag(FLAG_REF_FETCH, false);
}
void put(String column, Object value) {
Field field = field(column);
if (field == null) {
field = new Field();
column = StringPool.get(column);
}
field.setChanged(true);
field.setValue(value);
fields.put(column, field);
}
/**
* Sets the specified column to value.
*
* If the value refers to a {@link Record} it is stored as a reference,
* and the column is assigned the value of the Record's primary key.
*
* @param column the column name
* @param value the value
*/
public void set(String column, Object value) {
assertNotReadOnly();
put(column, value);
}
|
public void set(Composite.Value value) {
|
jajja/jorm
|
src/main/java/com/jajja/jorm/RecordBatch.java
|
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class Field {
// private Object value = null;
// private boolean isChanged = false;
//
// Field() {}
//
// public Field(Object value) {
// setValue(value);
// setChanged(true);
// }
//
// void setValue(Object value) {
// this.value = value;
// }
//
// public <T> T value(Class<T> type) {
// return convert(value, type);
// }
//
// public Object rawValue() {
// return value;
// }
//
// public Record record() {
// return (value instanceof Record) ? ((Record)value) : null;
// }
//
// // @SuppressWarnings("unchecked")
// // public <T extends Record> T ref(Transaction t, Class<T> clazz) throws SQLException {
// // if (record() == null) {
// // if (isReferenceCacheOnly) {
// // return null;
// // }
// // if (!flag(FLAG_REF_FETCH)) {
// // throw new IllegalAccessError("Reference fetching is disabled");
// // }
// // setValue(t.findById((Class<? extends Record>)clazz, value));
// // }
// // return (T)record();
// // }
//
// public Object dereference() {
// return (value instanceof Record) ? ((Record)value).id() : value;
// }
//
// void setChanged(boolean isChanged) {
// this.isChanged = isChanged;
// }
//
// public boolean isChanged() {
// return isChanged;
// }
//
// @Override
// public String toString() {
// return String.format("Field [value => %s, isChanged => %s]", value, isChanged);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Field) {
// Object v = ((Field)obj).value;
// return (value == v || (value != null && value.equals(v)));
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// return (value != null) ? value.hashCode() : 0;
// }
// }
//
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class NamedField {
// private String name;
// private Field field;
//
// public NamedField(Entry<String, Field> e) {
// this.name = e.getKey();
// this.field = e.getValue();
// }
//
// public String name() {
// return name;
// }
//
// public Field field() {
// return field;
// }
// }
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import com.jajja.jorm.Row.Field;
import com.jajja.jorm.Row.NamedField;
|
return records;
}
public Class<? extends Record> clazz() {
return template.getClass();
}
public int size() {
return size;
}
public Iterable<Slice<T>> slice(int size) {
return new Slicer<T>(this, records, size);
}
public static class Slice<TT extends Record> extends ArrayList<TT> {
private static final long serialVersionUID = 1L;
private final RecordBatch<TT> batch;
private Set<String> columns;
private Set<String> dirtyColumns;
public Slice(RecordBatch<TT> batch, int size) {
super(size);
this.batch = batch;
}
private void complete() {
columns = new HashSet<String>();
dirtyColumns = new HashSet<String>();
for (TT record : this) {
|
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class Field {
// private Object value = null;
// private boolean isChanged = false;
//
// Field() {}
//
// public Field(Object value) {
// setValue(value);
// setChanged(true);
// }
//
// void setValue(Object value) {
// this.value = value;
// }
//
// public <T> T value(Class<T> type) {
// return convert(value, type);
// }
//
// public Object rawValue() {
// return value;
// }
//
// public Record record() {
// return (value instanceof Record) ? ((Record)value) : null;
// }
//
// // @SuppressWarnings("unchecked")
// // public <T extends Record> T ref(Transaction t, Class<T> clazz) throws SQLException {
// // if (record() == null) {
// // if (isReferenceCacheOnly) {
// // return null;
// // }
// // if (!flag(FLAG_REF_FETCH)) {
// // throw new IllegalAccessError("Reference fetching is disabled");
// // }
// // setValue(t.findById((Class<? extends Record>)clazz, value));
// // }
// // return (T)record();
// // }
//
// public Object dereference() {
// return (value instanceof Record) ? ((Record)value).id() : value;
// }
//
// void setChanged(boolean isChanged) {
// this.isChanged = isChanged;
// }
//
// public boolean isChanged() {
// return isChanged;
// }
//
// @Override
// public String toString() {
// return String.format("Field [value => %s, isChanged => %s]", value, isChanged);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Field) {
// Object v = ((Field)obj).value;
// return (value == v || (value != null && value.equals(v)));
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// return (value != null) ? value.hashCode() : 0;
// }
// }
//
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class NamedField {
// private String name;
// private Field field;
//
// public NamedField(Entry<String, Field> e) {
// this.name = e.getKey();
// this.field = e.getValue();
// }
//
// public String name() {
// return name;
// }
//
// public Field field() {
// return field;
// }
// }
// Path: src/main/java/com/jajja/jorm/RecordBatch.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import com.jajja.jorm.Row.Field;
import com.jajja.jorm.Row.NamedField;
return records;
}
public Class<? extends Record> clazz() {
return template.getClass();
}
public int size() {
return size;
}
public Iterable<Slice<T>> slice(int size) {
return new Slicer<T>(this, records, size);
}
public static class Slice<TT extends Record> extends ArrayList<TT> {
private static final long serialVersionUID = 1L;
private final RecordBatch<TT> batch;
private Set<String> columns;
private Set<String> dirtyColumns;
public Slice(RecordBatch<TT> batch, int size) {
super(size);
this.batch = batch;
}
private void complete() {
columns = new HashSet<String>();
dirtyColumns = new HashSet<String>();
for (TT record : this) {
|
for (NamedField e : record.fields()) {
|
jajja/jorm
|
src/main/java/com/jajja/jorm/RecordBatch.java
|
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class Field {
// private Object value = null;
// private boolean isChanged = false;
//
// Field() {}
//
// public Field(Object value) {
// setValue(value);
// setChanged(true);
// }
//
// void setValue(Object value) {
// this.value = value;
// }
//
// public <T> T value(Class<T> type) {
// return convert(value, type);
// }
//
// public Object rawValue() {
// return value;
// }
//
// public Record record() {
// return (value instanceof Record) ? ((Record)value) : null;
// }
//
// // @SuppressWarnings("unchecked")
// // public <T extends Record> T ref(Transaction t, Class<T> clazz) throws SQLException {
// // if (record() == null) {
// // if (isReferenceCacheOnly) {
// // return null;
// // }
// // if (!flag(FLAG_REF_FETCH)) {
// // throw new IllegalAccessError("Reference fetching is disabled");
// // }
// // setValue(t.findById((Class<? extends Record>)clazz, value));
// // }
// // return (T)record();
// // }
//
// public Object dereference() {
// return (value instanceof Record) ? ((Record)value).id() : value;
// }
//
// void setChanged(boolean isChanged) {
// this.isChanged = isChanged;
// }
//
// public boolean isChanged() {
// return isChanged;
// }
//
// @Override
// public String toString() {
// return String.format("Field [value => %s, isChanged => %s]", value, isChanged);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Field) {
// Object v = ((Field)obj).value;
// return (value == v || (value != null && value.equals(v)));
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// return (value != null) ? value.hashCode() : 0;
// }
// }
//
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class NamedField {
// private String name;
// private Field field;
//
// public NamedField(Entry<String, Field> e) {
// this.name = e.getKey();
// this.field = e.getValue();
// }
//
// public String name() {
// return name;
// }
//
// public Field field() {
// return field;
// }
// }
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import com.jajja.jorm.Row.Field;
import com.jajja.jorm.Row.NamedField;
|
public Class<? extends Record> clazz() {
return template.getClass();
}
public int size() {
return size;
}
public Iterable<Slice<T>> slice(int size) {
return new Slicer<T>(this, records, size);
}
public static class Slice<TT extends Record> extends ArrayList<TT> {
private static final long serialVersionUID = 1L;
private final RecordBatch<TT> batch;
private Set<String> columns;
private Set<String> dirtyColumns;
public Slice(RecordBatch<TT> batch, int size) {
super(size);
this.batch = batch;
}
private void complete() {
columns = new HashSet<String>();
dirtyColumns = new HashSet<String>();
for (TT record : this) {
for (NamedField e : record.fields()) {
String column = e.name();
|
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class Field {
// private Object value = null;
// private boolean isChanged = false;
//
// Field() {}
//
// public Field(Object value) {
// setValue(value);
// setChanged(true);
// }
//
// void setValue(Object value) {
// this.value = value;
// }
//
// public <T> T value(Class<T> type) {
// return convert(value, type);
// }
//
// public Object rawValue() {
// return value;
// }
//
// public Record record() {
// return (value instanceof Record) ? ((Record)value) : null;
// }
//
// // @SuppressWarnings("unchecked")
// // public <T extends Record> T ref(Transaction t, Class<T> clazz) throws SQLException {
// // if (record() == null) {
// // if (isReferenceCacheOnly) {
// // return null;
// // }
// // if (!flag(FLAG_REF_FETCH)) {
// // throw new IllegalAccessError("Reference fetching is disabled");
// // }
// // setValue(t.findById((Class<? extends Record>)clazz, value));
// // }
// // return (T)record();
// // }
//
// public Object dereference() {
// return (value instanceof Record) ? ((Record)value).id() : value;
// }
//
// void setChanged(boolean isChanged) {
// this.isChanged = isChanged;
// }
//
// public boolean isChanged() {
// return isChanged;
// }
//
// @Override
// public String toString() {
// return String.format("Field [value => %s, isChanged => %s]", value, isChanged);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Field) {
// Object v = ((Field)obj).value;
// return (value == v || (value != null && value.equals(v)));
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// return (value != null) ? value.hashCode() : 0;
// }
// }
//
// Path: src/main/java/com/jajja/jorm/Row.java
// public static class NamedField {
// private String name;
// private Field field;
//
// public NamedField(Entry<String, Field> e) {
// this.name = e.getKey();
// this.field = e.getValue();
// }
//
// public String name() {
// return name;
// }
//
// public Field field() {
// return field;
// }
// }
// Path: src/main/java/com/jajja/jorm/RecordBatch.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import com.jajja.jorm.Row.Field;
import com.jajja.jorm.Row.NamedField;
public Class<? extends Record> clazz() {
return template.getClass();
}
public int size() {
return size;
}
public Iterable<Slice<T>> slice(int size) {
return new Slicer<T>(this, records, size);
}
public static class Slice<TT extends Record> extends ArrayList<TT> {
private static final long serialVersionUID = 1L;
private final RecordBatch<TT> batch;
private Set<String> columns;
private Set<String> dirtyColumns;
public Slice(RecordBatch<TT> batch, int size) {
super(size);
this.batch = batch;
}
private void complete() {
columns = new HashSet<String>();
dirtyColumns = new HashSet<String>();
for (TT record : this) {
for (NamedField e : record.fields()) {
String column = e.name();
|
Field field = e.field();
|
jajja/jorm
|
src/main/java/com/jajja/jorm/Cache.java
|
// Path: src/main/java/com/jajja/jorm/Composite.java
// public static class Value {
// private Composite composite;
// private Object[] values;
//
// private Value(Composite composite, Object ... values) {
// this.composite = composite;
// this.values = values;
// }
//
// public Composite getComposite() {
// return composite;
// }
//
// public Object[] getValues() {
// return values;
// }
//
// public Object getValue() {
// if (!isSingle()) {
// throw new RuntimeException("Not a single column key");
// }
// return values[0];
// }
//
// private int getOffset(String column) {
// for (int i = 0; i < composite.columns.length; i++) {
// if (composite.columns[i].equals(column)) {
// return i;
// }
// }
// return -1;
// }
//
// @SuppressWarnings("unchecked")
// public <T> T get(String column, Class<T> clazz) {
// int offset = getOffset(column);
// if (offset < 0) {
// throw new IllegalArgumentException("No such column " + column);
// }
// Object value = values[offset];
// if (value == null) {
// return null;
// }
// return (T)value;
// }
//
// public boolean isSingle() {
// return values.length == 1;
// }
//
// @Override
// public int hashCode() {
// int hashCode = 0;
// for (Object value : values) {
// if (value != null) {
// hashCode += value.hashCode();
// }
// }
// return hashCode;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Value) {
// Value v = (Value)obj;
// if (values.length != v.values.length) {
// return false;
// }
// for (int i = 0; i < values.length; i++) {
// if (!((values[i] == v.values[i]) || (values[i] != null && values[i].equals(v.values[i])))) {
// return false;
// }
// }
// return true;
// }
// return false;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder(16 * values.length);
// sb.append("{");
// boolean isFirst = true;
// for (Object value : values) {
// if (!isFirst) {
// sb.append(", ");
// } else {
// isFirst = false;
// }
// sb.append(value);
// }
// sb.append("}");
// return sb.toString();
// }
// }
|
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import com.jajja.jorm.Composite.Value;
|
/*
* Copyright (C) 2013 Jajja Communications AB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jajja.jorm;
/**
* A record cache implementation, using LRU.
*
* @see Record
* @author Andreas Allerdahl <andreas.allerdahl@jajja.com>
* @since 1.0.0
*/
public class Cache<C extends Record> {
private Lru<Object> map;
private Class<C> clazz;
private Set<Composite> additionalComposites = new HashSet<Composite>();
private Composite primaryKey;
// <additionalComposite, <additionalValue, primaryKeyValue>>
|
// Path: src/main/java/com/jajja/jorm/Composite.java
// public static class Value {
// private Composite composite;
// private Object[] values;
//
// private Value(Composite composite, Object ... values) {
// this.composite = composite;
// this.values = values;
// }
//
// public Composite getComposite() {
// return composite;
// }
//
// public Object[] getValues() {
// return values;
// }
//
// public Object getValue() {
// if (!isSingle()) {
// throw new RuntimeException("Not a single column key");
// }
// return values[0];
// }
//
// private int getOffset(String column) {
// for (int i = 0; i < composite.columns.length; i++) {
// if (composite.columns[i].equals(column)) {
// return i;
// }
// }
// return -1;
// }
//
// @SuppressWarnings("unchecked")
// public <T> T get(String column, Class<T> clazz) {
// int offset = getOffset(column);
// if (offset < 0) {
// throw new IllegalArgumentException("No such column " + column);
// }
// Object value = values[offset];
// if (value == null) {
// return null;
// }
// return (T)value;
// }
//
// public boolean isSingle() {
// return values.length == 1;
// }
//
// @Override
// public int hashCode() {
// int hashCode = 0;
// for (Object value : values) {
// if (value != null) {
// hashCode += value.hashCode();
// }
// }
// return hashCode;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Value) {
// Value v = (Value)obj;
// if (values.length != v.values.length) {
// return false;
// }
// for (int i = 0; i < values.length; i++) {
// if (!((values[i] == v.values[i]) || (values[i] != null && values[i].equals(v.values[i])))) {
// return false;
// }
// }
// return true;
// }
// return false;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder(16 * values.length);
// sb.append("{");
// boolean isFirst = true;
// for (Object value : values) {
// if (!isFirst) {
// sb.append(", ");
// } else {
// isFirst = false;
// }
// sb.append(value);
// }
// sb.append("}");
// return sb.toString();
// }
// }
// Path: src/main/java/com/jajja/jorm/Cache.java
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import com.jajja.jorm.Composite.Value;
/*
* Copyright (C) 2013 Jajja Communications AB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jajja.jorm;
/**
* A record cache implementation, using LRU.
*
* @see Record
* @author Andreas Allerdahl <andreas.allerdahl@jajja.com>
* @since 1.0.0
*/
public class Cache<C extends Record> {
private Lru<Object> map;
private Class<C> clazz;
private Set<Composite> additionalComposites = new HashSet<Composite>();
private Composite primaryKey;
// <additionalComposite, <additionalValue, primaryKeyValue>>
|
private Map<Composite, Map<Composite.Value, Composite.Value>> additionalMap = new HashMap<Composite, Map<Composite.Value, Composite.Value>>();
|
Samistine/BloodMoon
|
src/main/java/uk/co/jacekk/bukkit/bloodmoon/entity/BloodMoonEntityType.java
|
// Path: src/main/java/uk/co/jacekk/bukkit/bloodmoon/exceptions/EntityRegistrationException.java
// public class EntityRegistrationException extends Exception {
//
// private static final long serialVersionUID = 5269865836575653186L;
//
// public EntityRegistrationException(String message) {
// super(message);
// }
//
// public EntityRegistrationException(String message, Exception cause) {
// super(message, cause);
// }
//
// }
|
import net.minecraft.server.v1_8_R3.*;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.entity.EntityType;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import uk.co.jacekk.bukkit.baseplugin.util.ReflectionUtils;
import uk.co.jacekk.bukkit.bloodmoon.exceptions.EntityRegistrationException;
import java.util.List;
import java.util.Map;
|
package uk.co.jacekk.bukkit.bloodmoon.entity;
public enum BloodMoonEntityType {
CREEPER("Creeper", 50, EntityType.CREEPER, net.minecraft.server.v1_8_R3.EntityCreeper.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityCreeper.class),
ENDERMAN("Enderman", 58, EntityType.ENDERMAN, net.minecraft.server.v1_8_R3.EntityEnderman.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityEnderman.class),
SKELETON("Skeleton", 51, EntityType.SKELETON, net.minecraft.server.v1_8_R3.EntitySkeleton.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntitySkeleton.class),
SPIDER("Spider", 52, EntityType.SPIDER, net.minecraft.server.v1_8_R3.EntitySpider.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntitySpider.class),
ZOMBIE("Zombie", 54, EntityType.ZOMBIE, net.minecraft.server.v1_8_R3.EntityZombie.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityZombie.class),
GHAST("Ghast", 56, EntityType.GHAST, net.minecraft.server.v1_8_R3.EntityGhast.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityGhast.class),
BLAZE("Blaze", 61, EntityType.BLAZE, net.minecraft.server.v1_8_R3.EntityBlaze.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityBlaze.class),
WITHER("WitherBoss", 64, EntityType.WITHER, net.minecraft.server.v1_8_R3.EntityWither.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityWither.class),
WITCH("Witch", 66, EntityType.WITCH, net.minecraft.server.v1_8_R3.EntityWitch.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityWitch.class),
GIANT_ZOMBIE("Giant", 53, EntityType.GIANT, net.minecraft.server.v1_8_R3.EntityGiantZombie.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityGiantZombie.class);
private final String name;
private final int id;
private final EntityType entityType;
private final Class<? extends EntityInsentient> nmsClass;
private final Class<? extends EntityInsentient> bloodMoonClass;
private static boolean registered = false;
private BloodMoonEntityType(String name, int id, EntityType entityType, Class<? extends EntityInsentient> nmsClass, Class<? extends EntityInsentient> bloodMoonClass) {
this.name = name;
this.id = id;
this.entityType = entityType;
this.nmsClass = nmsClass;
this.bloodMoonClass = bloodMoonClass;
}
@SuppressWarnings("unchecked")
|
// Path: src/main/java/uk/co/jacekk/bukkit/bloodmoon/exceptions/EntityRegistrationException.java
// public class EntityRegistrationException extends Exception {
//
// private static final long serialVersionUID = 5269865836575653186L;
//
// public EntityRegistrationException(String message) {
// super(message);
// }
//
// public EntityRegistrationException(String message, Exception cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/uk/co/jacekk/bukkit/bloodmoon/entity/BloodMoonEntityType.java
import net.minecraft.server.v1_8_R3.*;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.entity.EntityType;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import uk.co.jacekk.bukkit.baseplugin.util.ReflectionUtils;
import uk.co.jacekk.bukkit.bloodmoon.exceptions.EntityRegistrationException;
import java.util.List;
import java.util.Map;
package uk.co.jacekk.bukkit.bloodmoon.entity;
public enum BloodMoonEntityType {
CREEPER("Creeper", 50, EntityType.CREEPER, net.minecraft.server.v1_8_R3.EntityCreeper.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityCreeper.class),
ENDERMAN("Enderman", 58, EntityType.ENDERMAN, net.minecraft.server.v1_8_R3.EntityEnderman.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityEnderman.class),
SKELETON("Skeleton", 51, EntityType.SKELETON, net.minecraft.server.v1_8_R3.EntitySkeleton.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntitySkeleton.class),
SPIDER("Spider", 52, EntityType.SPIDER, net.minecraft.server.v1_8_R3.EntitySpider.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntitySpider.class),
ZOMBIE("Zombie", 54, EntityType.ZOMBIE, net.minecraft.server.v1_8_R3.EntityZombie.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityZombie.class),
GHAST("Ghast", 56, EntityType.GHAST, net.minecraft.server.v1_8_R3.EntityGhast.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityGhast.class),
BLAZE("Blaze", 61, EntityType.BLAZE, net.minecraft.server.v1_8_R3.EntityBlaze.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityBlaze.class),
WITHER("WitherBoss", 64, EntityType.WITHER, net.minecraft.server.v1_8_R3.EntityWither.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityWither.class),
WITCH("Witch", 66, EntityType.WITCH, net.minecraft.server.v1_8_R3.EntityWitch.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityWitch.class),
GIANT_ZOMBIE("Giant", 53, EntityType.GIANT, net.minecraft.server.v1_8_R3.EntityGiantZombie.class, uk.co.jacekk.bukkit.bloodmoon.nms.EntityGiantZombie.class);
private final String name;
private final int id;
private final EntityType entityType;
private final Class<? extends EntityInsentient> nmsClass;
private final Class<? extends EntityInsentient> bloodMoonClass;
private static boolean registered = false;
private BloodMoonEntityType(String name, int id, EntityType entityType, Class<? extends EntityInsentient> nmsClass, Class<? extends EntityInsentient> bloodMoonClass) {
this.name = name;
this.id = id;
this.entityType = entityType;
this.nmsClass = nmsClass;
this.bloodMoonClass = bloodMoonClass;
}
@SuppressWarnings("unchecked")
|
public static void registerEntities() throws EntityRegistrationException {
|
mercyblitz/confucius-commons
|
confucius-commons-tools/confucius-commons-tools-attach/src/main/java/org/confucius/commons/tools/attach/LocalVirtualMachineTemplate.java
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/management/ManagementUtils.java
// public abstract class ManagementUtils {
//
// /**
// * {@link RuntimeMXBean}
// */
// private final static RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
//
// /**
// * "jvm" Field name
// */
// private final static String JVM_FIELD_NAME = "jvm";
// /**
// * sun.management.ManagementFactory.jvm
// */
// final static Object jvm = initJvm();
// /**
// * "getProcessId" Method name
// */
// private final static String GET_PROCESS_ID_METHOD_NAME = "getProcessId";
// /**
// * "getProcessId" Method
// */
// final static Method getProcessIdMethod = initGetProcessIdMethod();
//
//
// private static Object initJvm() {
// Object jvm = null;
// Field jvmField = null;
// if (runtimeMXBean != null) {
// try {
// jvmField = runtimeMXBean.getClass().getDeclaredField(JVM_FIELD_NAME);
// jvmField.setAccessible(true);
// jvm = jvmField.get(runtimeMXBean);
// } catch (Exception ignored) {
// System.err.printf("The Field[name : %s] can't be found in RuntimeMXBean Class[%s]!\n", JVM_FIELD_NAME, runtimeMXBean.getClass());
// }
// }
// return jvm;
// }
//
// private static Method initGetProcessIdMethod() {
// Class<?> jvmClass = jvm.getClass();
//
// Method getProcessIdMethod = null;
// try {
// getProcessIdMethod = jvmClass.getDeclaredMethod(GET_PROCESS_ID_METHOD_NAME);
// getProcessIdMethod.setAccessible(true);
// } catch (Exception ignored) {
// System.err.printf("%s method can't be found in class[%s]!\n", GET_PROCESS_ID_METHOD_NAME, jvmClass.getName());
// }
// return getProcessIdMethod;
// }
//
// private static Object invoke(Method method, Object object, Object... arguments) {
// Object result = null;
// try {
// if (!method.isAccessible()) {
// method.setAccessible(true);
// }
// result = method.invoke(object, arguments);
// } catch (Exception ignored) {
// System.err.printf("%s method[arguments : %s] can't be invoked in object[%s]!\n",
// method.getName(), Arrays.asList(arguments), object);
// }
//
// return result;
// }
//
// /**
// * Get the process ID of current JVM
// *
// * @return If can't get the process ID , return <code>-1</code>
// */
// public static int getCurrentProcessId() {
// int processId = -1;
// Object result = invoke(getProcessIdMethod, jvm);
// if (result instanceof Integer) {
// processId = (Integer) result;
// } else {
// // no guarantee
// String name = runtimeMXBean.getName();
// String processIdValue = StringUtils.substringBefore(name, "@");
// if (NumberUtils.isNumber(processIdValue)) {
// processId = Integer.parseInt(processIdValue);
// }
// }
// return processId;
// }
//
// }
|
import org.confucius.commons.lang.management.ManagementUtils;
|
package org.confucius.commons.tools.attach;
/**
* Local {@link VirtualMachineTemplate}
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @version 1.0.0
* @see LocalVirtualMachineTemplate
* @since 1.0.0
*/
public class LocalVirtualMachineTemplate extends VirtualMachineTemplate {
public LocalVirtualMachineTemplate() {
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/management/ManagementUtils.java
// public abstract class ManagementUtils {
//
// /**
// * {@link RuntimeMXBean}
// */
// private final static RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
//
// /**
// * "jvm" Field name
// */
// private final static String JVM_FIELD_NAME = "jvm";
// /**
// * sun.management.ManagementFactory.jvm
// */
// final static Object jvm = initJvm();
// /**
// * "getProcessId" Method name
// */
// private final static String GET_PROCESS_ID_METHOD_NAME = "getProcessId";
// /**
// * "getProcessId" Method
// */
// final static Method getProcessIdMethod = initGetProcessIdMethod();
//
//
// private static Object initJvm() {
// Object jvm = null;
// Field jvmField = null;
// if (runtimeMXBean != null) {
// try {
// jvmField = runtimeMXBean.getClass().getDeclaredField(JVM_FIELD_NAME);
// jvmField.setAccessible(true);
// jvm = jvmField.get(runtimeMXBean);
// } catch (Exception ignored) {
// System.err.printf("The Field[name : %s] can't be found in RuntimeMXBean Class[%s]!\n", JVM_FIELD_NAME, runtimeMXBean.getClass());
// }
// }
// return jvm;
// }
//
// private static Method initGetProcessIdMethod() {
// Class<?> jvmClass = jvm.getClass();
//
// Method getProcessIdMethod = null;
// try {
// getProcessIdMethod = jvmClass.getDeclaredMethod(GET_PROCESS_ID_METHOD_NAME);
// getProcessIdMethod.setAccessible(true);
// } catch (Exception ignored) {
// System.err.printf("%s method can't be found in class[%s]!\n", GET_PROCESS_ID_METHOD_NAME, jvmClass.getName());
// }
// return getProcessIdMethod;
// }
//
// private static Object invoke(Method method, Object object, Object... arguments) {
// Object result = null;
// try {
// if (!method.isAccessible()) {
// method.setAccessible(true);
// }
// result = method.invoke(object, arguments);
// } catch (Exception ignored) {
// System.err.printf("%s method[arguments : %s] can't be invoked in object[%s]!\n",
// method.getName(), Arrays.asList(arguments), object);
// }
//
// return result;
// }
//
// /**
// * Get the process ID of current JVM
// *
// * @return If can't get the process ID , return <code>-1</code>
// */
// public static int getCurrentProcessId() {
// int processId = -1;
// Object result = invoke(getProcessIdMethod, jvm);
// if (result instanceof Integer) {
// processId = (Integer) result;
// } else {
// // no guarantee
// String name = runtimeMXBean.getName();
// String processIdValue = StringUtils.substringBefore(name, "@");
// if (NumberUtils.isNumber(processIdValue)) {
// processId = Integer.parseInt(processIdValue);
// }
// }
// return processId;
// }
//
// }
// Path: confucius-commons-tools/confucius-commons-tools-attach/src/main/java/org/confucius/commons/tools/attach/LocalVirtualMachineTemplate.java
import org.confucius.commons.lang.management.ManagementUtils;
package org.confucius.commons.tools.attach;
/**
* Local {@link VirtualMachineTemplate}
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @version 1.0.0
* @see LocalVirtualMachineTemplate
* @since 1.0.0
*/
public class LocalVirtualMachineTemplate extends VirtualMachineTemplate {
public LocalVirtualMachineTemplate() {
|
super(String.valueOf(ManagementUtils.getCurrentProcessId()));
|
mercyblitz/confucius-commons
|
confucius-commons-lang/src/test/java/org/confucius/commons/lang/ClassLoaderUtilsTest.java
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/constants/FileSuffixConstants.java
// public interface FileSuffixConstants {
//
// /**
// * Jar File suffix : ".jar"
// */
// String JAR = Constants.DOT + ProtocolConstants.JAR;
//
// /**
// * War File suffix : ".jar"
// */
// String WAR = Constants.DOT + ProtocolConstants.WAR;
//
// /**
// * Ear File suffix : ".jar"
// */
// String EAR = Constants.DOT + ProtocolConstants.EAR;
//
// /**
// * Class File suffix : ".class"
// *
// * @since 1.0.0
// */
// String CLASS = Constants.DOT + Constants.CLASS;
// }
|
import com.google.common.collect.Sets;
import junit.framework.Assert;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.confucius.commons.lang.constants.FileSuffixConstants;
import org.junit.Test;
import java.io.IOException;
import java.lang.management.ClassLoadingMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
|
resourceName = "///////META-INF//abc\\/def";
resolvedResourceName = ClassLoaderUtils.ResourceType.DEFAULT.resolve(resourceName);
Assert.assertEquals(expectedResourceName, resolvedResourceName);
resourceName = "java.lang.String.class";
expectedResourceName = "java/lang/String.class";
resolvedResourceName = ClassLoaderUtils.ResourceType.CLASS.resolve(resourceName);
Assert.assertEquals(expectedResourceName, resolvedResourceName);
resourceName = "java.lang";
expectedResourceName = "java/lang/";
resolvedResourceName = ClassLoaderUtils.ResourceType.PACKAGE.resolve(resourceName);
Assert.assertEquals(expectedResourceName, resolvedResourceName);
}
@Test
public void testGetClassResource() {
URL classResourceURL = ClassLoaderUtils.getClassResource(classLoader, ClassLoaderUtilsTest.class);
Assert.assertNotNull(classResourceURL);
echo(classResourceURL);
classResourceURL = ClassLoaderUtils.getClassResource(classLoader, String.class.getName());
Assert.assertNotNull(classResourceURL);
echo(classResourceURL);
}
@Test
public void testGetResource() {
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/constants/FileSuffixConstants.java
// public interface FileSuffixConstants {
//
// /**
// * Jar File suffix : ".jar"
// */
// String JAR = Constants.DOT + ProtocolConstants.JAR;
//
// /**
// * War File suffix : ".jar"
// */
// String WAR = Constants.DOT + ProtocolConstants.WAR;
//
// /**
// * Ear File suffix : ".jar"
// */
// String EAR = Constants.DOT + ProtocolConstants.EAR;
//
// /**
// * Class File suffix : ".class"
// *
// * @since 1.0.0
// */
// String CLASS = Constants.DOT + Constants.CLASS;
// }
// Path: confucius-commons-lang/src/test/java/org/confucius/commons/lang/ClassLoaderUtilsTest.java
import com.google.common.collect.Sets;
import junit.framework.Assert;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.confucius.commons.lang.constants.FileSuffixConstants;
import org.junit.Test;
import java.io.IOException;
import java.lang.management.ClassLoadingMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
resourceName = "///////META-INF//abc\\/def";
resolvedResourceName = ClassLoaderUtils.ResourceType.DEFAULT.resolve(resourceName);
Assert.assertEquals(expectedResourceName, resolvedResourceName);
resourceName = "java.lang.String.class";
expectedResourceName = "java/lang/String.class";
resolvedResourceName = ClassLoaderUtils.ResourceType.CLASS.resolve(resourceName);
Assert.assertEquals(expectedResourceName, resolvedResourceName);
resourceName = "java.lang";
expectedResourceName = "java/lang/";
resolvedResourceName = ClassLoaderUtils.ResourceType.PACKAGE.resolve(resourceName);
Assert.assertEquals(expectedResourceName, resolvedResourceName);
}
@Test
public void testGetClassResource() {
URL classResourceURL = ClassLoaderUtils.getClassResource(classLoader, ClassLoaderUtilsTest.class);
Assert.assertNotNull(classResourceURL);
echo(classResourceURL);
classResourceURL = ClassLoaderUtils.getClassResource(classLoader, String.class.getName());
Assert.assertNotNull(classResourceURL);
echo(classResourceURL);
}
@Test
public void testGetResource() {
|
URL resourceURL = ClassLoaderUtils.getResource(classLoader, ClassLoaderUtilsTest.class.getName() + FileSuffixConstants.CLASS);
|
mercyblitz/confucius-commons
|
confucius-commons-util/src/main/java/org/confucius/commons/util/os/windows/WindowsRegistry.java
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/constants/PathConstants.java
// public interface PathConstants {
//
// /**
// * Slash : <code>"/"</code>
// */
// String SLASH = "/";
// /**
// * Double Slash : <code>"//"</code>
// */
// String DOUBLE_SLASH = SLASH + SLASH;
// /**
// * Back Slash : <code>"\"</code>
// */
// String BACK_SLASH = "\\";
//
// }
|
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.confucius.commons.lang.constants.PathConstants;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Method;
import java.util.StringTokenizer;
import java.util.prefs.Preferences;
|
StringBuffer result = new StringBuffer();
for (int i = 0; i < array.length - 1; i++) {
result.append((char) array[i]);
}
return result.toString();
}
/**
* Get Windows Registry <tt>HKEY_CURRENT_USER</tt> Singleton
*
* @return non-null return
* @throws UnsupportedOperationException
* If Non-Windows OS executes current method
*/
@Nonnull
public static WindowsRegistry currentUser() throws UnsupportedOperationException {
if (!SystemUtils.IS_OS_WINDOWS) {
String message = String.format("Non Windows System");
throw new UnsupportedOperationException(message);
}
return CURRENT_USER;
}
/**
* Returns Windows absolute relativePath of the current node as a byte array. Java "/" separator is transformed into
* Windows "\".
*
* @see Preferences#absolutePath()
*/
protected byte[] windowsAbsolutePath(String relativePath) {
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/constants/PathConstants.java
// public interface PathConstants {
//
// /**
// * Slash : <code>"/"</code>
// */
// String SLASH = "/";
// /**
// * Double Slash : <code>"//"</code>
// */
// String DOUBLE_SLASH = SLASH + SLASH;
// /**
// * Back Slash : <code>"\"</code>
// */
// String BACK_SLASH = "\\";
//
// }
// Path: confucius-commons-util/src/main/java/org/confucius/commons/util/os/windows/WindowsRegistry.java
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.confucius.commons.lang.constants.PathConstants;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Method;
import java.util.StringTokenizer;
import java.util.prefs.Preferences;
StringBuffer result = new StringBuffer();
for (int i = 0; i < array.length - 1; i++) {
result.append((char) array[i]);
}
return result.toString();
}
/**
* Get Windows Registry <tt>HKEY_CURRENT_USER</tt> Singleton
*
* @return non-null return
* @throws UnsupportedOperationException
* If Non-Windows OS executes current method
*/
@Nonnull
public static WindowsRegistry currentUser() throws UnsupportedOperationException {
if (!SystemUtils.IS_OS_WINDOWS) {
String message = String.format("Non Windows System");
throw new UnsupportedOperationException(message);
}
return CURRENT_USER;
}
/**
* Returns Windows absolute relativePath of the current node as a byte array. Java "/" separator is transformed into
* Windows "\".
*
* @see Preferences#absolutePath()
*/
protected byte[] windowsAbsolutePath(String relativePath) {
|
String resolvedPath = StringUtils.replace(relativePath, PathConstants.SLASH, PathConstants.BACK_SLASH);
|
mercyblitz/confucius-commons
|
confucius-commons-lang/src/main/java/org/confucius/commons/lang/io/scanner/Scanner.java
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/filter/Filter.java
// public interface Filter<T> {
//
// /**
// * Does accept filtered object?
// *
// * @param filteredObject
// * filtered object
// * @return
// */
// boolean accept(T filteredObject);
// }
|
import javax.annotation.Nonnull;
import java.util.Set;
import org.confucius.commons.lang.filter.Filter;
|
/**
*
*/
package org.confucius.commons.lang.io.scanner;
/**
* {@link Scanner}
*
* @param <S>
* the type of scanned source
* @param <R>
* the type of scan result
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @version 1.0.0
* @see Scanner
* @since 1.0.0
*/
public interface Scanner<S, R> {
/**
* Scan source to calculate result set
*
* @param source
* scanned source
* @return result set , non-null
* @throws IllegalArgumentException
* scanned source is not legal
* @throws IllegalStateException
* scanned source's state is not valid
*/
@Nonnull
Set<R> scan(S source) throws IllegalArgumentException, IllegalStateException;
/**
* Scan source to calculate result set with {@link Filter}
*
* @param source
* scanned source
* @param filter
* {@link Filter<R> filter} to accept result
* @return result set , non-null
* @throws IllegalArgumentException
* scanned source is not legal
* @throws IllegalStateException
* scanned source's state is not valid
*/
@Nonnull
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/filter/Filter.java
// public interface Filter<T> {
//
// /**
// * Does accept filtered object?
// *
// * @param filteredObject
// * filtered object
// * @return
// */
// boolean accept(T filteredObject);
// }
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/io/scanner/Scanner.java
import javax.annotation.Nonnull;
import java.util.Set;
import org.confucius.commons.lang.filter.Filter;
/**
*
*/
package org.confucius.commons.lang.io.scanner;
/**
* {@link Scanner}
*
* @param <S>
* the type of scanned source
* @param <R>
* the type of scan result
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @version 1.0.0
* @see Scanner
* @since 1.0.0
*/
public interface Scanner<S, R> {
/**
* Scan source to calculate result set
*
* @param source
* scanned source
* @return result set , non-null
* @throws IllegalArgumentException
* scanned source is not legal
* @throws IllegalStateException
* scanned source's state is not valid
*/
@Nonnull
Set<R> scan(S source) throws IllegalArgumentException, IllegalStateException;
/**
* Scan source to calculate result set with {@link Filter}
*
* @param source
* scanned source
* @param filter
* {@link Filter<R> filter} to accept result
* @return result set , non-null
* @throws IllegalArgumentException
* scanned source is not legal
* @throws IllegalStateException
* scanned source's state is not valid
*/
@Nonnull
|
Set<R> scan(S source, Filter<R> filter) throws IllegalArgumentException, IllegalStateException;
|
mercyblitz/confucius-commons
|
confucius-commons-lang/src/main/java/org/confucius/commons/lang/filter/ClassFileJarEntryFilter.java
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/constants/FileSuffixConstants.java
// public interface FileSuffixConstants {
//
// /**
// * Jar File suffix : ".jar"
// */
// String JAR = Constants.DOT + ProtocolConstants.JAR;
//
// /**
// * War File suffix : ".jar"
// */
// String WAR = Constants.DOT + ProtocolConstants.WAR;
//
// /**
// * Ear File suffix : ".jar"
// */
// String EAR = Constants.DOT + ProtocolConstants.EAR;
//
// /**
// * Class File suffix : ".class"
// *
// * @since 1.0.0
// */
// String CLASS = Constants.DOT + Constants.CLASS;
// }
|
import org.confucius.commons.lang.constants.FileSuffixConstants;
import java.util.jar.JarEntry;
|
/**
*
*/
package org.confucius.commons.lang.filter;
/**
* Class File {@link JarEntryFilter}
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @version 1.0.0
* @see ClassFileJarEntryFilter
* @since 1.0.0
*/
public class ClassFileJarEntryFilter implements JarEntryFilter {
/**
* {@link ClassFileJarEntryFilter} Singleton instance
*/
public static final ClassFileJarEntryFilter INSTANCE = new ClassFileJarEntryFilter();
protected ClassFileJarEntryFilter() {
}
@Override
public boolean accept(JarEntry jarEntry) {
|
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/constants/FileSuffixConstants.java
// public interface FileSuffixConstants {
//
// /**
// * Jar File suffix : ".jar"
// */
// String JAR = Constants.DOT + ProtocolConstants.JAR;
//
// /**
// * War File suffix : ".jar"
// */
// String WAR = Constants.DOT + ProtocolConstants.WAR;
//
// /**
// * Ear File suffix : ".jar"
// */
// String EAR = Constants.DOT + ProtocolConstants.EAR;
//
// /**
// * Class File suffix : ".class"
// *
// * @since 1.0.0
// */
// String CLASS = Constants.DOT + Constants.CLASS;
// }
// Path: confucius-commons-lang/src/main/java/org/confucius/commons/lang/filter/ClassFileJarEntryFilter.java
import org.confucius.commons.lang.constants.FileSuffixConstants;
import java.util.jar.JarEntry;
/**
*
*/
package org.confucius.commons.lang.filter;
/**
* Class File {@link JarEntryFilter}
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @version 1.0.0
* @see ClassFileJarEntryFilter
* @since 1.0.0
*/
public class ClassFileJarEntryFilter implements JarEntryFilter {
/**
* {@link ClassFileJarEntryFilter} Singleton instance
*/
public static final ClassFileJarEntryFilter INSTANCE = new ClassFileJarEntryFilter();
protected ClassFileJarEntryFilter() {
}
@Override
public boolean accept(JarEntry jarEntry) {
|
return !jarEntry.isDirectory() && jarEntry.getName().endsWith(FileSuffixConstants.CLASS);
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/GameThread.java
|
// Path: src/com/sproutlife/model/step/GameStep.java
// public static enum StepType {
// GAME_STEP,
// LIFE_STEP,
// SPROUT_STEP,
// MUTATION_STEP,
// PRUNE_STEP,
// COLOR_STEP,
// STEP_BUNDLE
// }
//
// Path: src/com/sproutlife/model/step/GameStepEvent.java
// public class GameStepEvent {
//
// StepType stepType;
//
// public GameStepEvent(StepType stepType) {
// this.stepType = stepType;
// }
//
// public StepType getStepType() {
// return stepType;
// }
// }
//
// Path: src/com/sproutlife/model/step/GameStepListener.java
// public interface GameStepListener {
//
// public void stepPerformed(GameStepEvent event);
//
// }
|
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.sproutlife.model.step.GameStep.StepType;
import com.sproutlife.model.step.GameStepEvent;
import com.sproutlife.model.step.GameStepListener;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model;
public class GameThread {
private boolean playGame = false;
Thread innerThread;
|
// Path: src/com/sproutlife/model/step/GameStep.java
// public static enum StepType {
// GAME_STEP,
// LIFE_STEP,
// SPROUT_STEP,
// MUTATION_STEP,
// PRUNE_STEP,
// COLOR_STEP,
// STEP_BUNDLE
// }
//
// Path: src/com/sproutlife/model/step/GameStepEvent.java
// public class GameStepEvent {
//
// StepType stepType;
//
// public GameStepEvent(StepType stepType) {
// this.stepType = stepType;
// }
//
// public StepType getStepType() {
// return stepType;
// }
// }
//
// Path: src/com/sproutlife/model/step/GameStepListener.java
// public interface GameStepListener {
//
// public void stepPerformed(GameStepEvent event);
//
// }
// Path: src/com/sproutlife/model/GameThread.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.sproutlife.model.step.GameStep.StepType;
import com.sproutlife.model.step.GameStepEvent;
import com.sproutlife.model.step.GameStepListener;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model;
public class GameThread {
private boolean playGame = false;
Thread innerThread;
|
List<GameStepListener> gameStepListeners;
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/GameThread.java
|
// Path: src/com/sproutlife/model/step/GameStep.java
// public static enum StepType {
// GAME_STEP,
// LIFE_STEP,
// SPROUT_STEP,
// MUTATION_STEP,
// PRUNE_STEP,
// COLOR_STEP,
// STEP_BUNDLE
// }
//
// Path: src/com/sproutlife/model/step/GameStepEvent.java
// public class GameStepEvent {
//
// StepType stepType;
//
// public GameStepEvent(StepType stepType) {
// this.stepType = stepType;
// }
//
// public StepType getStepType() {
// return stepType;
// }
// }
//
// Path: src/com/sproutlife/model/step/GameStepListener.java
// public interface GameStepListener {
//
// public void stepPerformed(GameStepEvent event);
//
// }
|
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.sproutlife.model.step.GameStep.StepType;
import com.sproutlife.model.step.GameStepEvent;
import com.sproutlife.model.step.GameStepListener;
|
public boolean isPlaying() {
return playGame;
}
public int getSleepDelay() {
return sleepDelay;
}
public void setSleepDelay(int sleepDelay) {
this.sleepDelay = sleepDelay;
}
public int getIterationsPerEvent() {
return iterationsPerEvent;
}
public void setIterationsPerEvent(int iterationsPerEvent) {
this.iterationsPerEvent = iterationsPerEvent;
}
public void addGameStepListener(GameStepListener gameStepListener) {
gameStepListeners.add(gameStepListener);
}
public void removeGameStepListener(GameStepListener gameStepListener) {
gameStepListeners.remove(gameStepListener);
}
private void fireStepBundlePerformed() {
for (GameStepListener gsl : gameStepListeners) {
|
// Path: src/com/sproutlife/model/step/GameStep.java
// public static enum StepType {
// GAME_STEP,
// LIFE_STEP,
// SPROUT_STEP,
// MUTATION_STEP,
// PRUNE_STEP,
// COLOR_STEP,
// STEP_BUNDLE
// }
//
// Path: src/com/sproutlife/model/step/GameStepEvent.java
// public class GameStepEvent {
//
// StepType stepType;
//
// public GameStepEvent(StepType stepType) {
// this.stepType = stepType;
// }
//
// public StepType getStepType() {
// return stepType;
// }
// }
//
// Path: src/com/sproutlife/model/step/GameStepListener.java
// public interface GameStepListener {
//
// public void stepPerformed(GameStepEvent event);
//
// }
// Path: src/com/sproutlife/model/GameThread.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.sproutlife.model.step.GameStep.StepType;
import com.sproutlife.model.step.GameStepEvent;
import com.sproutlife.model.step.GameStepListener;
public boolean isPlaying() {
return playGame;
}
public int getSleepDelay() {
return sleepDelay;
}
public void setSleepDelay(int sleepDelay) {
this.sleepDelay = sleepDelay;
}
public int getIterationsPerEvent() {
return iterationsPerEvent;
}
public void setIterationsPerEvent(int iterationsPerEvent) {
this.iterationsPerEvent = iterationsPerEvent;
}
public void addGameStepListener(GameStepListener gameStepListener) {
gameStepListeners.add(gameStepListener);
}
public void removeGameStepListener(GameStepListener gameStepListener) {
gameStepListeners.remove(gameStepListener);
}
private void fireStepBundlePerformed() {
for (GameStepListener gsl : gameStepListeners) {
|
GameStepEvent event = new GameStepEvent(StepType.STEP_BUNDLE);
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/GameThread.java
|
// Path: src/com/sproutlife/model/step/GameStep.java
// public static enum StepType {
// GAME_STEP,
// LIFE_STEP,
// SPROUT_STEP,
// MUTATION_STEP,
// PRUNE_STEP,
// COLOR_STEP,
// STEP_BUNDLE
// }
//
// Path: src/com/sproutlife/model/step/GameStepEvent.java
// public class GameStepEvent {
//
// StepType stepType;
//
// public GameStepEvent(StepType stepType) {
// this.stepType = stepType;
// }
//
// public StepType getStepType() {
// return stepType;
// }
// }
//
// Path: src/com/sproutlife/model/step/GameStepListener.java
// public interface GameStepListener {
//
// public void stepPerformed(GameStepEvent event);
//
// }
|
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.sproutlife.model.step.GameStep.StepType;
import com.sproutlife.model.step.GameStepEvent;
import com.sproutlife.model.step.GameStepListener;
|
public boolean isPlaying() {
return playGame;
}
public int getSleepDelay() {
return sleepDelay;
}
public void setSleepDelay(int sleepDelay) {
this.sleepDelay = sleepDelay;
}
public int getIterationsPerEvent() {
return iterationsPerEvent;
}
public void setIterationsPerEvent(int iterationsPerEvent) {
this.iterationsPerEvent = iterationsPerEvent;
}
public void addGameStepListener(GameStepListener gameStepListener) {
gameStepListeners.add(gameStepListener);
}
public void removeGameStepListener(GameStepListener gameStepListener) {
gameStepListeners.remove(gameStepListener);
}
private void fireStepBundlePerformed() {
for (GameStepListener gsl : gameStepListeners) {
|
// Path: src/com/sproutlife/model/step/GameStep.java
// public static enum StepType {
// GAME_STEP,
// LIFE_STEP,
// SPROUT_STEP,
// MUTATION_STEP,
// PRUNE_STEP,
// COLOR_STEP,
// STEP_BUNDLE
// }
//
// Path: src/com/sproutlife/model/step/GameStepEvent.java
// public class GameStepEvent {
//
// StepType stepType;
//
// public GameStepEvent(StepType stepType) {
// this.stepType = stepType;
// }
//
// public StepType getStepType() {
// return stepType;
// }
// }
//
// Path: src/com/sproutlife/model/step/GameStepListener.java
// public interface GameStepListener {
//
// public void stepPerformed(GameStepEvent event);
//
// }
// Path: src/com/sproutlife/model/GameThread.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.sproutlife.model.step.GameStep.StepType;
import com.sproutlife.model.step.GameStepEvent;
import com.sproutlife.model.step.GameStepListener;
public boolean isPlaying() {
return playGame;
}
public int getSleepDelay() {
return sleepDelay;
}
public void setSleepDelay(int sleepDelay) {
this.sleepDelay = sleepDelay;
}
public int getIterationsPerEvent() {
return iterationsPerEvent;
}
public void setIterationsPerEvent(int iterationsPerEvent) {
this.iterationsPerEvent = iterationsPerEvent;
}
public void addGameStepListener(GameStepListener gameStepListener) {
gameStepListeners.add(gameStepListener);
}
public void removeGameStepListener(GameStepListener gameStepListener) {
gameStepListeners.remove(gameStepListener);
}
private void fireStepBundlePerformed() {
for (GameStepListener gsl : gameStepListeners) {
|
GameStepEvent event = new GameStepEvent(StepType.STEP_BUNDLE);
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/GliderRpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class GliderRpPattern extends SeedSproutPattern {
public GliderRpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/GliderRpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class GliderRpPattern extends SeedSproutPattern {
public GliderRpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/Square2RpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class Square2RpPattern extends SeedSproutPattern {
public Square2RpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/Square2RpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class Square2RpPattern extends SeedSproutPattern {
public Square2RpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/BoxlidRpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class BoxlidRpPattern extends SeedSproutPattern {
public BoxlidRpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/BoxlidRpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class BoxlidRpPattern extends SeedSproutPattern {
public BoxlidRpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/echosystem/Organism.java
|
// Path: src/com/sproutlife/model/GameClock.java
// public class GameClock {
// private int time;
//
// public GameClock() {
// time = 0;
// }
//
// public int getTime() {
// return time;
// }
//
// void increment() {
// time++;
// }
//
// void reset() {
// this.time = 0;
// }
// }
//
// Path: src/com/sproutlife/model/seed/Seed.java
// public class Seed {
//
// protected SeedSproutPattern pattern;
// public Point position = null;
// public Rotation rotation;
// public int seedBorder = 1;
// public Point parentPosition;
// //Organism organism;
//
// public Seed(SeedSproutPattern pattern, Rotation r) {
// this.pattern = pattern;
// this.rotation = r;
// }
//
// public Seed(SeedSproutPattern pattern) {
// this(pattern, Rotations.get());
// }
//
// public Rotation getRotation() {
// return rotation;
// }
//
// public Point getPosition() {
// return position;
// }
//
// public void setPosition(int x, int y) {
// this.position = new Point(x,y);
// }
//
// public int getSeedBorder() {
// return seedBorder;
// }
//
// public void setSeedBorder(int b) {
// this.seedBorder = b;
// }
//
// public Point getParentPosition() {
// return parentPosition;
// }
//
// public void setParentPosition(Point parentPosition) {
// this.parentPosition = parentPosition;
// }
// /*
// public Organism getOrganism() {
// return organism;
// }
//
// public void setOrganism(Organism organism) {
// this.organism = organism;
// }
// */
//
// public SeedSproutPattern getSeedSproutPattern() {
// return pattern;
// }
//
// public BitPattern getSeedPattern() {
// return pattern.getSeedPattern();
// }
//
// public BitPattern getSproutPattern() {
// return pattern.getSproutPattern();
// }
//
// public boolean getSeedBit(int x, int y) {
// return getSeedPattern().getBit(x, y, getRotation());
// }
//
// public boolean getSproutBit(int x, int y) {
// return getSproutPattern().getBit(x, y, getRotation());
// }
//
// public int getSeedWidth() {
// return getSeedPattern().getWidth(getRotation());
// }
//
// public int getSeedHeight() {
// return getSeedPattern().getHeight(getRotation());
// }
//
// public int getSproutWidth() {
// return getSproutPattern().getWidth(getRotation());
// }
//
// public int getSproutHeight() {
// return getSproutPattern().getHeight(getRotation());
// }
//
// public Point getSproutOffset() {
// return Rotations.offsetToBoard(
// pattern.getSproutOffset(),
// getSeedPattern(),
// getSproutPattern(),
// getRotation());
// }
//
// public Point getSproutPosition() {
// Point sproutOffset = getSproutOffset();
// return new Point(position.x + sproutOffset.x, position.y + sproutOffset.y);
// }
//
// public Point getSproutCenter() {
// Point sproutPosition = getSproutPosition();
// Point sproutCenter = getSproutPattern().getCenter(getRotation());
//
// int ssX = sproutPosition.x+sproutCenter.x;
// int ssY = sproutPosition.y+sproutCenter.y;
//
// return new Point(ssX, ssY);
// }
//
// public Point getSeedOnBit() {
// return pattern.getSeedPattern().getOnBit(getRotation());
// }
//
// public Point getSeedOnPosition() {
// Point pos = this.getPosition();
// Point onOffset = this.getSeedOnBit();
// return new Point(pos.x+onOffset.x,pos.y+onOffset.y);
// }
// }
|
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import com.sproutlife.model.GameClock;
import com.sproutlife.model.seed.Seed;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.echosystem;
/**
* Organisms are a collection of Cells. They keep track of the location where
* they were born, the seed from which they sprouted, their parents and
* children. They have a genome which stores their mutations.
*
* Organisms have a lot going on, and some experimental attributes are placed in
* OrgAttributes to keep the code a bit cleaner.
*
* @author Alex Shapiro
*/
public class Organism {
private int id;
private ArrayList<Cell> cells;
private Organism parent;
private ArrayList<Organism> children;
private Genome genome;
|
// Path: src/com/sproutlife/model/GameClock.java
// public class GameClock {
// private int time;
//
// public GameClock() {
// time = 0;
// }
//
// public int getTime() {
// return time;
// }
//
// void increment() {
// time++;
// }
//
// void reset() {
// this.time = 0;
// }
// }
//
// Path: src/com/sproutlife/model/seed/Seed.java
// public class Seed {
//
// protected SeedSproutPattern pattern;
// public Point position = null;
// public Rotation rotation;
// public int seedBorder = 1;
// public Point parentPosition;
// //Organism organism;
//
// public Seed(SeedSproutPattern pattern, Rotation r) {
// this.pattern = pattern;
// this.rotation = r;
// }
//
// public Seed(SeedSproutPattern pattern) {
// this(pattern, Rotations.get());
// }
//
// public Rotation getRotation() {
// return rotation;
// }
//
// public Point getPosition() {
// return position;
// }
//
// public void setPosition(int x, int y) {
// this.position = new Point(x,y);
// }
//
// public int getSeedBorder() {
// return seedBorder;
// }
//
// public void setSeedBorder(int b) {
// this.seedBorder = b;
// }
//
// public Point getParentPosition() {
// return parentPosition;
// }
//
// public void setParentPosition(Point parentPosition) {
// this.parentPosition = parentPosition;
// }
// /*
// public Organism getOrganism() {
// return organism;
// }
//
// public void setOrganism(Organism organism) {
// this.organism = organism;
// }
// */
//
// public SeedSproutPattern getSeedSproutPattern() {
// return pattern;
// }
//
// public BitPattern getSeedPattern() {
// return pattern.getSeedPattern();
// }
//
// public BitPattern getSproutPattern() {
// return pattern.getSproutPattern();
// }
//
// public boolean getSeedBit(int x, int y) {
// return getSeedPattern().getBit(x, y, getRotation());
// }
//
// public boolean getSproutBit(int x, int y) {
// return getSproutPattern().getBit(x, y, getRotation());
// }
//
// public int getSeedWidth() {
// return getSeedPattern().getWidth(getRotation());
// }
//
// public int getSeedHeight() {
// return getSeedPattern().getHeight(getRotation());
// }
//
// public int getSproutWidth() {
// return getSproutPattern().getWidth(getRotation());
// }
//
// public int getSproutHeight() {
// return getSproutPattern().getHeight(getRotation());
// }
//
// public Point getSproutOffset() {
// return Rotations.offsetToBoard(
// pattern.getSproutOffset(),
// getSeedPattern(),
// getSproutPattern(),
// getRotation());
// }
//
// public Point getSproutPosition() {
// Point sproutOffset = getSproutOffset();
// return new Point(position.x + sproutOffset.x, position.y + sproutOffset.y);
// }
//
// public Point getSproutCenter() {
// Point sproutPosition = getSproutPosition();
// Point sproutCenter = getSproutPattern().getCenter(getRotation());
//
// int ssX = sproutPosition.x+sproutCenter.x;
// int ssY = sproutPosition.y+sproutCenter.y;
//
// return new Point(ssX, ssY);
// }
//
// public Point getSeedOnBit() {
// return pattern.getSeedPattern().getOnBit(getRotation());
// }
//
// public Point getSeedOnPosition() {
// Point pos = this.getPosition();
// Point onOffset = this.getSeedOnBit();
// return new Point(pos.x+onOffset.x,pos.y+onOffset.y);
// }
// }
// Path: src/com/sproutlife/model/echosystem/Organism.java
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import com.sproutlife.model.GameClock;
import com.sproutlife.model.seed.Seed;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.echosystem;
/**
* Organisms are a collection of Cells. They keep track of the location where
* they were born, the seed from which they sprouted, their parents and
* children. They have a genome which stores their mutations.
*
* Organisms have a lot going on, and some experimental attributes are placed in
* OrgAttributes to keep the code a bit cleaner.
*
* @author Alex Shapiro
*/
public class Organism {
private int id;
private ArrayList<Cell> cells;
private Organism parent;
private ArrayList<Organism> children;
private Genome genome;
|
private Seed seed;
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/echosystem/Organism.java
|
// Path: src/com/sproutlife/model/GameClock.java
// public class GameClock {
// private int time;
//
// public GameClock() {
// time = 0;
// }
//
// public int getTime() {
// return time;
// }
//
// void increment() {
// time++;
// }
//
// void reset() {
// this.time = 0;
// }
// }
//
// Path: src/com/sproutlife/model/seed/Seed.java
// public class Seed {
//
// protected SeedSproutPattern pattern;
// public Point position = null;
// public Rotation rotation;
// public int seedBorder = 1;
// public Point parentPosition;
// //Organism organism;
//
// public Seed(SeedSproutPattern pattern, Rotation r) {
// this.pattern = pattern;
// this.rotation = r;
// }
//
// public Seed(SeedSproutPattern pattern) {
// this(pattern, Rotations.get());
// }
//
// public Rotation getRotation() {
// return rotation;
// }
//
// public Point getPosition() {
// return position;
// }
//
// public void setPosition(int x, int y) {
// this.position = new Point(x,y);
// }
//
// public int getSeedBorder() {
// return seedBorder;
// }
//
// public void setSeedBorder(int b) {
// this.seedBorder = b;
// }
//
// public Point getParentPosition() {
// return parentPosition;
// }
//
// public void setParentPosition(Point parentPosition) {
// this.parentPosition = parentPosition;
// }
// /*
// public Organism getOrganism() {
// return organism;
// }
//
// public void setOrganism(Organism organism) {
// this.organism = organism;
// }
// */
//
// public SeedSproutPattern getSeedSproutPattern() {
// return pattern;
// }
//
// public BitPattern getSeedPattern() {
// return pattern.getSeedPattern();
// }
//
// public BitPattern getSproutPattern() {
// return pattern.getSproutPattern();
// }
//
// public boolean getSeedBit(int x, int y) {
// return getSeedPattern().getBit(x, y, getRotation());
// }
//
// public boolean getSproutBit(int x, int y) {
// return getSproutPattern().getBit(x, y, getRotation());
// }
//
// public int getSeedWidth() {
// return getSeedPattern().getWidth(getRotation());
// }
//
// public int getSeedHeight() {
// return getSeedPattern().getHeight(getRotation());
// }
//
// public int getSproutWidth() {
// return getSproutPattern().getWidth(getRotation());
// }
//
// public int getSproutHeight() {
// return getSproutPattern().getHeight(getRotation());
// }
//
// public Point getSproutOffset() {
// return Rotations.offsetToBoard(
// pattern.getSproutOffset(),
// getSeedPattern(),
// getSproutPattern(),
// getRotation());
// }
//
// public Point getSproutPosition() {
// Point sproutOffset = getSproutOffset();
// return new Point(position.x + sproutOffset.x, position.y + sproutOffset.y);
// }
//
// public Point getSproutCenter() {
// Point sproutPosition = getSproutPosition();
// Point sproutCenter = getSproutPattern().getCenter(getRotation());
//
// int ssX = sproutPosition.x+sproutCenter.x;
// int ssY = sproutPosition.y+sproutCenter.y;
//
// return new Point(ssX, ssY);
// }
//
// public Point getSeedOnBit() {
// return pattern.getSeedPattern().getOnBit(getRotation());
// }
//
// public Point getSeedOnPosition() {
// Point pos = this.getPosition();
// Point onOffset = this.getSeedOnBit();
// return new Point(pos.x+onOffset.x,pos.y+onOffset.y);
// }
// }
|
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import com.sproutlife.model.GameClock;
import com.sproutlife.model.seed.Seed;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.echosystem;
/**
* Organisms are a collection of Cells. They keep track of the location where
* they were born, the seed from which they sprouted, their parents and
* children. They have a genome which stores their mutations.
*
* Organisms have a lot going on, and some experimental attributes are placed in
* OrgAttributes to keep the code a bit cleaner.
*
* @author Alex Shapiro
*/
public class Organism {
private int id;
private ArrayList<Cell> cells;
private Organism parent;
private ArrayList<Organism> children;
private Genome genome;
private Seed seed;
//The clock lets us know the organism's age, so we can just track when it was born
|
// Path: src/com/sproutlife/model/GameClock.java
// public class GameClock {
// private int time;
//
// public GameClock() {
// time = 0;
// }
//
// public int getTime() {
// return time;
// }
//
// void increment() {
// time++;
// }
//
// void reset() {
// this.time = 0;
// }
// }
//
// Path: src/com/sproutlife/model/seed/Seed.java
// public class Seed {
//
// protected SeedSproutPattern pattern;
// public Point position = null;
// public Rotation rotation;
// public int seedBorder = 1;
// public Point parentPosition;
// //Organism organism;
//
// public Seed(SeedSproutPattern pattern, Rotation r) {
// this.pattern = pattern;
// this.rotation = r;
// }
//
// public Seed(SeedSproutPattern pattern) {
// this(pattern, Rotations.get());
// }
//
// public Rotation getRotation() {
// return rotation;
// }
//
// public Point getPosition() {
// return position;
// }
//
// public void setPosition(int x, int y) {
// this.position = new Point(x,y);
// }
//
// public int getSeedBorder() {
// return seedBorder;
// }
//
// public void setSeedBorder(int b) {
// this.seedBorder = b;
// }
//
// public Point getParentPosition() {
// return parentPosition;
// }
//
// public void setParentPosition(Point parentPosition) {
// this.parentPosition = parentPosition;
// }
// /*
// public Organism getOrganism() {
// return organism;
// }
//
// public void setOrganism(Organism organism) {
// this.organism = organism;
// }
// */
//
// public SeedSproutPattern getSeedSproutPattern() {
// return pattern;
// }
//
// public BitPattern getSeedPattern() {
// return pattern.getSeedPattern();
// }
//
// public BitPattern getSproutPattern() {
// return pattern.getSproutPattern();
// }
//
// public boolean getSeedBit(int x, int y) {
// return getSeedPattern().getBit(x, y, getRotation());
// }
//
// public boolean getSproutBit(int x, int y) {
// return getSproutPattern().getBit(x, y, getRotation());
// }
//
// public int getSeedWidth() {
// return getSeedPattern().getWidth(getRotation());
// }
//
// public int getSeedHeight() {
// return getSeedPattern().getHeight(getRotation());
// }
//
// public int getSproutWidth() {
// return getSproutPattern().getWidth(getRotation());
// }
//
// public int getSproutHeight() {
// return getSproutPattern().getHeight(getRotation());
// }
//
// public Point getSproutOffset() {
// return Rotations.offsetToBoard(
// pattern.getSproutOffset(),
// getSeedPattern(),
// getSproutPattern(),
// getRotation());
// }
//
// public Point getSproutPosition() {
// Point sproutOffset = getSproutOffset();
// return new Point(position.x + sproutOffset.x, position.y + sproutOffset.y);
// }
//
// public Point getSproutCenter() {
// Point sproutPosition = getSproutPosition();
// Point sproutCenter = getSproutPattern().getCenter(getRotation());
//
// int ssX = sproutPosition.x+sproutCenter.x;
// int ssY = sproutPosition.y+sproutCenter.y;
//
// return new Point(ssX, ssY);
// }
//
// public Point getSeedOnBit() {
// return pattern.getSeedPattern().getOnBit(getRotation());
// }
//
// public Point getSeedOnPosition() {
// Point pos = this.getPosition();
// Point onOffset = this.getSeedOnBit();
// return new Point(pos.x+onOffset.x,pos.y+onOffset.y);
// }
// }
// Path: src/com/sproutlife/model/echosystem/Organism.java
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import com.sproutlife.model.GameClock;
import com.sproutlife.model.seed.Seed;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.echosystem;
/**
* Organisms are a collection of Cells. They keep track of the location where
* they were born, the seed from which they sprouted, their parents and
* children. They have a genome which stores their mutations.
*
* Organisms have a lot going on, and some experimental attributes are placed in
* OrgAttributes to keep the code a bit cleaner.
*
* @author Alex Shapiro
*/
public class Organism {
private int id;
private ArrayList<Cell> cells;
private Organism parent;
private ArrayList<Organism> children;
private Genome genome;
private Seed seed;
//The clock lets us know the organism's age, so we can just track when it was born
|
public GameClock clock;
|
ShprAlex/SproutLife
|
src/com/sproutlife/renderer/colors/AngleColorModel.java
|
// Path: src/com/sproutlife/model/echosystem/Organism.java
// public class Organism {
// private int id;
// private ArrayList<Cell> cells;
// private Organism parent;
// private ArrayList<Organism> children;
// private Genome genome;
// private Seed seed;
//
// //The clock lets us know the organism's age, so we can just track when it was born
// public GameClock clock;
//
// // Lifespan isn's age, but a self destruct value above
// // which the organism is removed
// public int lifespan;
// private int born; //Game time when the organism was born.
// private boolean alive = true;
// private int timeOfDeath;
//
// private Point location;
// public int x; //duplicate location for shorter code
// public int y; //duplicate location for shorter code
//
// //Keep track of random and experimental attributes in separate class
// private OrgAttributes attributes;
//
// public Organism(int id, GameClock clock, int x, int y, Organism parent, Seed seed) {
// this.id = id;
// this.clock = clock;
// this.born = clock.getTime();
// this.parent = parent;
// this.children = new ArrayList<Organism>();
// this.setLocation(x, y);
// this.seed = seed;
// this.genome = new Genome();
// this.cells = new ArrayList<Cell>();
// this.timeOfDeath = -1;
// this.attributes = new OrgAttributes(this);
//
// if (parent!=null) {
// parent.addChild(this);
// this.genome = parent.getGenome().clone();
// this.lifespan = parent.lifespan;
// }
// }
//
// public int getId() {
// return id;
// }
//
// public void setLocation(int x, int y) {
// this.x = x;
// this.y = y;
// this.location = new Point(x,y);
// }
//
// public Point getLocation() {
// return location;
// }
//
// public Organism getParent() {
// return parent;
// }
//
// public void setParent(Organism parent) {
// this.parent = parent;
// }
//
// public ArrayList<Organism> getChildren() {
// return children;
// }
//
// public void addChild(Organism childOrg) {
// children.add(childOrg);
// }
//
// public void setSeed(Seed seed) {
// this.seed = seed;
// }
//
// public Seed getSeed() {
// return seed;
// }
//
// public GameClock getClock() {
// return clock;
// }
//
// public int getLifespan() {
// return lifespan;
// }
//
// public void setLifespan(int lifespan) {
// this.lifespan = lifespan;
// }
//
// public int getBorn() {
// return born;
// }
//
// /*
// * @return return the time since the organism was born, even if it's dead
// */
// public int getTimeSinceBorn() {
// return getClock().getTime() - this.born;
// }
//
// /*
// * @return if the organism is alive, return the time since it was born,
// * otherwise, return the age at which the organism died.
// */
// public int getAge() {
// if (isAlive()) {
// return getTimeSinceBorn();
// }
// else {
// return this.timeOfDeath - this.born;
// }
// }
//
// public OrgAttributes getAttributes() {
// return attributes;
// }
//
// public Genome getGenome() {
// return genome;
// }
//
// public List<Cell> getCells() {
// return cells;
// }
//
// public Cell addCell(int x, int y) {
// Cell c = new Cell(x, y, this);
// addCell(c);
// return c;
// }
//
// /*
// * Add a cell that's been created
// *
// * @param c - cell to add
// */
// public void addCell(Cell c) {
// cells.add(c);
// }
//
// /*
// * Create cell but don't add it;
// * @param x - the x coordinate of the cell
// * @param y - the y coordinate of the cell
// * @return Create but don't add the cell
// */
// public Cell createCell(int x, int y) {
// Cell c = new Cell(x, y, this);
// return c;
// }
//
// public Cell getCell(int x, int y) {
// for (Cell c: cells) {
// if (c.x ==x && c.y==y) {
// return c;
// }
// }
// return null;
// }
//
//
// public boolean removeCell(Cell c) {
// return cells.remove(c);
// }
//
// /*
// * @return the number of cells an organism has
// */
// public int size() {
// return cells.size();
// }
//
// public boolean removeFromTerritory(Cell c) {
// boolean result = getAttributes().territory.remove(c);
//
// return result;
// }
//
// public void setAlive(boolean alive) {
// this.alive = alive;
// }
//
// public boolean isAlive() {
// return alive && !(getTimeOfDeath()>0);
// }
//
// public int getTimeOfDeath() {
// return timeOfDeath;
// }
//
// public void setTimeOfDeath(int timeOfDeath) {
// this.timeOfDeath = timeOfDeath;
// }
//
// public boolean equals(Organism o) {
// return this.id == o.id;
// }
// }
|
import java.awt.Color;
import com.sproutlife.model.echosystem.Organism;
|
package com.sproutlife.renderer.colors;
public class AngleColorModel extends ColorModel {
private float primaryHue = 0f;
private float hueRange = 100;
@Override
public void setAttribute(String attribute, Object value) {
if (attribute.equals("primaryHue")) {
primaryHue = ((int) value)/360f;
}
if (attribute.equals("hueRange")) {
hueRange = (int) value;
}
}
@Override
public Color getBackgroundColor() {
switch (backgroundTheme) {
case black:
return Color.black;
default:
return Color.white;
}
}
@Override
|
// Path: src/com/sproutlife/model/echosystem/Organism.java
// public class Organism {
// private int id;
// private ArrayList<Cell> cells;
// private Organism parent;
// private ArrayList<Organism> children;
// private Genome genome;
// private Seed seed;
//
// //The clock lets us know the organism's age, so we can just track when it was born
// public GameClock clock;
//
// // Lifespan isn's age, but a self destruct value above
// // which the organism is removed
// public int lifespan;
// private int born; //Game time when the organism was born.
// private boolean alive = true;
// private int timeOfDeath;
//
// private Point location;
// public int x; //duplicate location for shorter code
// public int y; //duplicate location for shorter code
//
// //Keep track of random and experimental attributes in separate class
// private OrgAttributes attributes;
//
// public Organism(int id, GameClock clock, int x, int y, Organism parent, Seed seed) {
// this.id = id;
// this.clock = clock;
// this.born = clock.getTime();
// this.parent = parent;
// this.children = new ArrayList<Organism>();
// this.setLocation(x, y);
// this.seed = seed;
// this.genome = new Genome();
// this.cells = new ArrayList<Cell>();
// this.timeOfDeath = -1;
// this.attributes = new OrgAttributes(this);
//
// if (parent!=null) {
// parent.addChild(this);
// this.genome = parent.getGenome().clone();
// this.lifespan = parent.lifespan;
// }
// }
//
// public int getId() {
// return id;
// }
//
// public void setLocation(int x, int y) {
// this.x = x;
// this.y = y;
// this.location = new Point(x,y);
// }
//
// public Point getLocation() {
// return location;
// }
//
// public Organism getParent() {
// return parent;
// }
//
// public void setParent(Organism parent) {
// this.parent = parent;
// }
//
// public ArrayList<Organism> getChildren() {
// return children;
// }
//
// public void addChild(Organism childOrg) {
// children.add(childOrg);
// }
//
// public void setSeed(Seed seed) {
// this.seed = seed;
// }
//
// public Seed getSeed() {
// return seed;
// }
//
// public GameClock getClock() {
// return clock;
// }
//
// public int getLifespan() {
// return lifespan;
// }
//
// public void setLifespan(int lifespan) {
// this.lifespan = lifespan;
// }
//
// public int getBorn() {
// return born;
// }
//
// /*
// * @return return the time since the organism was born, even if it's dead
// */
// public int getTimeSinceBorn() {
// return getClock().getTime() - this.born;
// }
//
// /*
// * @return if the organism is alive, return the time since it was born,
// * otherwise, return the age at which the organism died.
// */
// public int getAge() {
// if (isAlive()) {
// return getTimeSinceBorn();
// }
// else {
// return this.timeOfDeath - this.born;
// }
// }
//
// public OrgAttributes getAttributes() {
// return attributes;
// }
//
// public Genome getGenome() {
// return genome;
// }
//
// public List<Cell> getCells() {
// return cells;
// }
//
// public Cell addCell(int x, int y) {
// Cell c = new Cell(x, y, this);
// addCell(c);
// return c;
// }
//
// /*
// * Add a cell that's been created
// *
// * @param c - cell to add
// */
// public void addCell(Cell c) {
// cells.add(c);
// }
//
// /*
// * Create cell but don't add it;
// * @param x - the x coordinate of the cell
// * @param y - the y coordinate of the cell
// * @return Create but don't add the cell
// */
// public Cell createCell(int x, int y) {
// Cell c = new Cell(x, y, this);
// return c;
// }
//
// public Cell getCell(int x, int y) {
// for (Cell c: cells) {
// if (c.x ==x && c.y==y) {
// return c;
// }
// }
// return null;
// }
//
//
// public boolean removeCell(Cell c) {
// return cells.remove(c);
// }
//
// /*
// * @return the number of cells an organism has
// */
// public int size() {
// return cells.size();
// }
//
// public boolean removeFromTerritory(Cell c) {
// boolean result = getAttributes().territory.remove(c);
//
// return result;
// }
//
// public void setAlive(boolean alive) {
// this.alive = alive;
// }
//
// public boolean isAlive() {
// return alive && !(getTimeOfDeath()>0);
// }
//
// public int getTimeOfDeath() {
// return timeOfDeath;
// }
//
// public void setTimeOfDeath(int timeOfDeath) {
// this.timeOfDeath = timeOfDeath;
// }
//
// public boolean equals(Organism o) {
// return this.id == o.id;
// }
// }
// Path: src/com/sproutlife/renderer/colors/AngleColorModel.java
import java.awt.Color;
import com.sproutlife.model.echosystem.Organism;
package com.sproutlife.renderer.colors;
public class AngleColorModel extends ColorModel {
private float primaryHue = 0f;
private float hueRange = 100;
@Override
public void setAttribute(String attribute, Object value) {
if (attribute.equals("primaryHue")) {
primaryHue = ((int) value)/360f;
}
if (attribute.equals("hueRange")) {
hueRange = (int) value;
}
}
@Override
public Color getBackgroundColor() {
switch (backgroundTheme) {
case black:
return Color.black;
default:
return Color.white;
}
}
@Override
|
public Color getCellColor(Organism o) {
|
ShprAlex/SproutLife
|
src/com/sproutlife/renderer/colors/BattleColorModel.java
|
// Path: src/com/sproutlife/model/echosystem/Organism.java
// public class Organism {
// private int id;
// private ArrayList<Cell> cells;
// private Organism parent;
// private ArrayList<Organism> children;
// private Genome genome;
// private Seed seed;
//
// //The clock lets us know the organism's age, so we can just track when it was born
// public GameClock clock;
//
// // Lifespan isn's age, but a self destruct value above
// // which the organism is removed
// public int lifespan;
// private int born; //Game time when the organism was born.
// private boolean alive = true;
// private int timeOfDeath;
//
// private Point location;
// public int x; //duplicate location for shorter code
// public int y; //duplicate location for shorter code
//
// //Keep track of random and experimental attributes in separate class
// private OrgAttributes attributes;
//
// public Organism(int id, GameClock clock, int x, int y, Organism parent, Seed seed) {
// this.id = id;
// this.clock = clock;
// this.born = clock.getTime();
// this.parent = parent;
// this.children = new ArrayList<Organism>();
// this.setLocation(x, y);
// this.seed = seed;
// this.genome = new Genome();
// this.cells = new ArrayList<Cell>();
// this.timeOfDeath = -1;
// this.attributes = new OrgAttributes(this);
//
// if (parent!=null) {
// parent.addChild(this);
// this.genome = parent.getGenome().clone();
// this.lifespan = parent.lifespan;
// }
// }
//
// public int getId() {
// return id;
// }
//
// public void setLocation(int x, int y) {
// this.x = x;
// this.y = y;
// this.location = new Point(x,y);
// }
//
// public Point getLocation() {
// return location;
// }
//
// public Organism getParent() {
// return parent;
// }
//
// public void setParent(Organism parent) {
// this.parent = parent;
// }
//
// public ArrayList<Organism> getChildren() {
// return children;
// }
//
// public void addChild(Organism childOrg) {
// children.add(childOrg);
// }
//
// public void setSeed(Seed seed) {
// this.seed = seed;
// }
//
// public Seed getSeed() {
// return seed;
// }
//
// public GameClock getClock() {
// return clock;
// }
//
// public int getLifespan() {
// return lifespan;
// }
//
// public void setLifespan(int lifespan) {
// this.lifespan = lifespan;
// }
//
// public int getBorn() {
// return born;
// }
//
// /*
// * @return return the time since the organism was born, even if it's dead
// */
// public int getTimeSinceBorn() {
// return getClock().getTime() - this.born;
// }
//
// /*
// * @return if the organism is alive, return the time since it was born,
// * otherwise, return the age at which the organism died.
// */
// public int getAge() {
// if (isAlive()) {
// return getTimeSinceBorn();
// }
// else {
// return this.timeOfDeath - this.born;
// }
// }
//
// public OrgAttributes getAttributes() {
// return attributes;
// }
//
// public Genome getGenome() {
// return genome;
// }
//
// public List<Cell> getCells() {
// return cells;
// }
//
// public Cell addCell(int x, int y) {
// Cell c = new Cell(x, y, this);
// addCell(c);
// return c;
// }
//
// /*
// * Add a cell that's been created
// *
// * @param c - cell to add
// */
// public void addCell(Cell c) {
// cells.add(c);
// }
//
// /*
// * Create cell but don't add it;
// * @param x - the x coordinate of the cell
// * @param y - the y coordinate of the cell
// * @return Create but don't add the cell
// */
// public Cell createCell(int x, int y) {
// Cell c = new Cell(x, y, this);
// return c;
// }
//
// public Cell getCell(int x, int y) {
// for (Cell c: cells) {
// if (c.x ==x && c.y==y) {
// return c;
// }
// }
// return null;
// }
//
//
// public boolean removeCell(Cell c) {
// return cells.remove(c);
// }
//
// /*
// * @return the number of cells an organism has
// */
// public int size() {
// return cells.size();
// }
//
// public boolean removeFromTerritory(Cell c) {
// boolean result = getAttributes().territory.remove(c);
//
// return result;
// }
//
// public void setAlive(boolean alive) {
// this.alive = alive;
// }
//
// public boolean isAlive() {
// return alive && !(getTimeOfDeath()>0);
// }
//
// public int getTimeOfDeath() {
// return timeOfDeath;
// }
//
// public void setTimeOfDeath(int timeOfDeath) {
// this.timeOfDeath = timeOfDeath;
// }
//
// public boolean equals(Organism o) {
// return this.id == o.id;
// }
// }
|
import java.awt.Color;
import com.sproutlife.model.echosystem.Organism;
|
package com.sproutlife.renderer.colors;
public class BattleColorModel extends ColorModel {
@Override
public Color getBackgroundColor() {
switch (backgroundTheme) {
case black:
return Color.black;
default:
return Color.white;
}
}
@Override
|
// Path: src/com/sproutlife/model/echosystem/Organism.java
// public class Organism {
// private int id;
// private ArrayList<Cell> cells;
// private Organism parent;
// private ArrayList<Organism> children;
// private Genome genome;
// private Seed seed;
//
// //The clock lets us know the organism's age, so we can just track when it was born
// public GameClock clock;
//
// // Lifespan isn's age, but a self destruct value above
// // which the organism is removed
// public int lifespan;
// private int born; //Game time when the organism was born.
// private boolean alive = true;
// private int timeOfDeath;
//
// private Point location;
// public int x; //duplicate location for shorter code
// public int y; //duplicate location for shorter code
//
// //Keep track of random and experimental attributes in separate class
// private OrgAttributes attributes;
//
// public Organism(int id, GameClock clock, int x, int y, Organism parent, Seed seed) {
// this.id = id;
// this.clock = clock;
// this.born = clock.getTime();
// this.parent = parent;
// this.children = new ArrayList<Organism>();
// this.setLocation(x, y);
// this.seed = seed;
// this.genome = new Genome();
// this.cells = new ArrayList<Cell>();
// this.timeOfDeath = -1;
// this.attributes = new OrgAttributes(this);
//
// if (parent!=null) {
// parent.addChild(this);
// this.genome = parent.getGenome().clone();
// this.lifespan = parent.lifespan;
// }
// }
//
// public int getId() {
// return id;
// }
//
// public void setLocation(int x, int y) {
// this.x = x;
// this.y = y;
// this.location = new Point(x,y);
// }
//
// public Point getLocation() {
// return location;
// }
//
// public Organism getParent() {
// return parent;
// }
//
// public void setParent(Organism parent) {
// this.parent = parent;
// }
//
// public ArrayList<Organism> getChildren() {
// return children;
// }
//
// public void addChild(Organism childOrg) {
// children.add(childOrg);
// }
//
// public void setSeed(Seed seed) {
// this.seed = seed;
// }
//
// public Seed getSeed() {
// return seed;
// }
//
// public GameClock getClock() {
// return clock;
// }
//
// public int getLifespan() {
// return lifespan;
// }
//
// public void setLifespan(int lifespan) {
// this.lifespan = lifespan;
// }
//
// public int getBorn() {
// return born;
// }
//
// /*
// * @return return the time since the organism was born, even if it's dead
// */
// public int getTimeSinceBorn() {
// return getClock().getTime() - this.born;
// }
//
// /*
// * @return if the organism is alive, return the time since it was born,
// * otherwise, return the age at which the organism died.
// */
// public int getAge() {
// if (isAlive()) {
// return getTimeSinceBorn();
// }
// else {
// return this.timeOfDeath - this.born;
// }
// }
//
// public OrgAttributes getAttributes() {
// return attributes;
// }
//
// public Genome getGenome() {
// return genome;
// }
//
// public List<Cell> getCells() {
// return cells;
// }
//
// public Cell addCell(int x, int y) {
// Cell c = new Cell(x, y, this);
// addCell(c);
// return c;
// }
//
// /*
// * Add a cell that's been created
// *
// * @param c - cell to add
// */
// public void addCell(Cell c) {
// cells.add(c);
// }
//
// /*
// * Create cell but don't add it;
// * @param x - the x coordinate of the cell
// * @param y - the y coordinate of the cell
// * @return Create but don't add the cell
// */
// public Cell createCell(int x, int y) {
// Cell c = new Cell(x, y, this);
// return c;
// }
//
// public Cell getCell(int x, int y) {
// for (Cell c: cells) {
// if (c.x ==x && c.y==y) {
// return c;
// }
// }
// return null;
// }
//
//
// public boolean removeCell(Cell c) {
// return cells.remove(c);
// }
//
// /*
// * @return the number of cells an organism has
// */
// public int size() {
// return cells.size();
// }
//
// public boolean removeFromTerritory(Cell c) {
// boolean result = getAttributes().territory.remove(c);
//
// return result;
// }
//
// public void setAlive(boolean alive) {
// this.alive = alive;
// }
//
// public boolean isAlive() {
// return alive && !(getTimeOfDeath()>0);
// }
//
// public int getTimeOfDeath() {
// return timeOfDeath;
// }
//
// public void setTimeOfDeath(int timeOfDeath) {
// this.timeOfDeath = timeOfDeath;
// }
//
// public boolean equals(Organism o) {
// return this.id == o.id;
// }
// }
// Path: src/com/sproutlife/renderer/colors/BattleColorModel.java
import java.awt.Color;
import com.sproutlife.model.echosystem.Organism;
package com.sproutlife.renderer.colors;
public class BattleColorModel extends ColorModel {
@Override
public Color getBackgroundColor() {
switch (backgroundTheme) {
case black:
return Color.black;
default:
return Color.white;
}
}
@Override
|
public Color getCellColor(Organism o) {
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/OnebitB1RpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class OnebitB1RpPattern extends SeedSproutPattern {
public OnebitB1RpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/OnebitB1RpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class OnebitB1RpPattern extends SeedSproutPattern {
public OnebitB1RpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/RpRpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class RpRpPattern extends SeedSproutPattern {
public RpRpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/RpRpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class RpRpPattern extends SeedSproutPattern {
public RpRpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/panel/GameFrame.java
|
// Path: src/com/sproutlife/SproutLife.java
// public class SproutLife {
// private static final int appMajorVersion = 1;
// private static final int appMinorVersion = 1;
// private static final int appRevision = 0;
//
// public static int getAppMajorVersion() {
// return appMajorVersion;
// }
//
// public static int getAppMinorVersion() {
// return appMinorVersion;
// }
//
// public static int getAppRevision() {
// return appRevision;
// }
//
// public static String getAppVersion() {
// return ""+getAppMajorVersion()+"."+getAppMinorVersion()+"."+getAppRevision();
// }
//
// public static void main(String[] args) {
// new GameController();
// }
// }
|
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import com.sproutlife.SproutLife;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.panel;
public class GameFrame extends JFrame {
private static final Dimension DEFAULT_WINDOW_SIZE = new Dimension(1292, 641);
private static final Dimension MINIMUM_WINDOW_SIZE = new Dimension(300, 300);
PanelController panelController;
public GameFrame(PanelController panelController) {
this.panelController = panelController;
initFrame();
setLayout(new BorderLayout(0, 0));
}
private void initFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
// Path: src/com/sproutlife/SproutLife.java
// public class SproutLife {
// private static final int appMajorVersion = 1;
// private static final int appMinorVersion = 1;
// private static final int appRevision = 0;
//
// public static int getAppMajorVersion() {
// return appMajorVersion;
// }
//
// public static int getAppMinorVersion() {
// return appMinorVersion;
// }
//
// public static int getAppRevision() {
// return appRevision;
// }
//
// public static String getAppVersion() {
// return ""+getAppMajorVersion()+"."+getAppMinorVersion()+"."+getAppRevision();
// }
//
// public static void main(String[] args) {
// new GameController();
// }
// }
// Path: src/com/sproutlife/panel/GameFrame.java
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import com.sproutlife.SproutLife;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.panel;
public class GameFrame extends JFrame {
private static final Dimension DEFAULT_WINDOW_SIZE = new Dimension(1292, 641);
private static final Dimension MINIMUM_WINDOW_SIZE = new Dimension(300, 300);
PanelController panelController;
public GameFrame(PanelController panelController) {
this.panelController = panelController;
initFrame();
setLayout(new BorderLayout(0, 0));
}
private void initFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
setTitle("SproutLife - Evolving Game of Life - V " + SproutLife.getAppVersion());
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/L2RpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class L2RpPattern extends SeedSproutPattern {
public L2RpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/L2RpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class L2RpPattern extends SeedSproutPattern {
public L2RpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/OnebitRpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class OnebitRpPattern extends SeedSproutPattern {
public OnebitRpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/OnebitRpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class OnebitRpPattern extends SeedSproutPattern {
public OnebitRpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/step/lifemode/FriendlyLife.java
|
// Path: src/com/sproutlife/model/GameModel.java
// public class GameModel {
// private Echosystem echosystem;
// private GameClock clock;
// private GameStep gameStep;
// private GameThread gameThread;
// private Settings settings;
// private Stats stats;
//
// public GameModel(Settings settings, ReentrantReadWriteLock interactionLock) {
// this.settings = settings;
// this.clock = new GameClock();
// echosystem = new Echosystem(clock);
// gameStep = new GameStep(this);
// gameThread = new GameThread(this, interactionLock);
// stats = new Stats(this);
// }
//
// public Echosystem getEchosystem() {
// return echosystem;
// }
//
// public Board getBoard() {
// return echosystem.getBoard();
// }
//
// public int getTime() {
// return clock.getTime();
// }
//
// public Stats getStats() {
// return stats;
// }
//
// public Settings getSettings() {
// return settings;
// }
//
// public GameThread getGameThread() {
// return gameThread;
// }
//
// private GameClock getClock() {
// return clock;
// }
//
// private void incrementTime() {
// clock.increment();
// }
//
// public void performGameStep() {
// incrementTime();
// gameStep.perform();
// }
//
// public void resetGame() {
// getEchosystem().resetCells();
// EchosystemUtils.pruneEmptyOrganisms(getEchosystem());
// getEchosystem().clearRetiredOrgs();
// getStats().reset();
// getClock().reset();
// }
//
// public void setPlayGame(boolean playGame) {
// gameThread.setPlayGame(playGame);
// }
//
// public boolean isPlaying() {
// return gameThread.isPlaying();
// }
//
// public void setGameStepListener(GameStepListener l) {
// if (gameThread == null) {
// return;
// }
// gameThread.addGameStepListener(l);
// }
// }
//
// Path: src/com/sproutlife/model/echosystem/Cell.java
// public class Cell extends Point {
//
// private Organism organism = null;
//
// public int age; // experimental
//
// boolean markedAsSeed;
//
// public Cell(int x, int y, Organism o) {
// super(x, y);
// this.organism = o;
// this.age = 1;
// this.markedAsSeed = false;
// }
//
// public boolean isMarkedAsSeed() {
// return markedAsSeed;
// }
//
// public void setMarkedAsSeed(boolean markedAsSeed) {
// this.markedAsSeed = markedAsSeed;
// }
//
// public Organism getOrganism() {
// return organism;
// }
//
// public boolean isSameOrganism(Cell c2) {
// return this.getOrganism().equals(c2.getOrganism());
// }
//
// }
|
import java.util.Collection;
import com.sproutlife.model.GameModel;
import com.sproutlife.model.echosystem.Cell;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.step.lifemode;
public class FriendlyLife extends ParallelLife {
public FriendlyLife(GameModel gameModel) {
super(gameModel);
}
|
// Path: src/com/sproutlife/model/GameModel.java
// public class GameModel {
// private Echosystem echosystem;
// private GameClock clock;
// private GameStep gameStep;
// private GameThread gameThread;
// private Settings settings;
// private Stats stats;
//
// public GameModel(Settings settings, ReentrantReadWriteLock interactionLock) {
// this.settings = settings;
// this.clock = new GameClock();
// echosystem = new Echosystem(clock);
// gameStep = new GameStep(this);
// gameThread = new GameThread(this, interactionLock);
// stats = new Stats(this);
// }
//
// public Echosystem getEchosystem() {
// return echosystem;
// }
//
// public Board getBoard() {
// return echosystem.getBoard();
// }
//
// public int getTime() {
// return clock.getTime();
// }
//
// public Stats getStats() {
// return stats;
// }
//
// public Settings getSettings() {
// return settings;
// }
//
// public GameThread getGameThread() {
// return gameThread;
// }
//
// private GameClock getClock() {
// return clock;
// }
//
// private void incrementTime() {
// clock.increment();
// }
//
// public void performGameStep() {
// incrementTime();
// gameStep.perform();
// }
//
// public void resetGame() {
// getEchosystem().resetCells();
// EchosystemUtils.pruneEmptyOrganisms(getEchosystem());
// getEchosystem().clearRetiredOrgs();
// getStats().reset();
// getClock().reset();
// }
//
// public void setPlayGame(boolean playGame) {
// gameThread.setPlayGame(playGame);
// }
//
// public boolean isPlaying() {
// return gameThread.isPlaying();
// }
//
// public void setGameStepListener(GameStepListener l) {
// if (gameThread == null) {
// return;
// }
// gameThread.addGameStepListener(l);
// }
// }
//
// Path: src/com/sproutlife/model/echosystem/Cell.java
// public class Cell extends Point {
//
// private Organism organism = null;
//
// public int age; // experimental
//
// boolean markedAsSeed;
//
// public Cell(int x, int y, Organism o) {
// super(x, y);
// this.organism = o;
// this.age = 1;
// this.markedAsSeed = false;
// }
//
// public boolean isMarkedAsSeed() {
// return markedAsSeed;
// }
//
// public void setMarkedAsSeed(boolean markedAsSeed) {
// this.markedAsSeed = markedAsSeed;
// }
//
// public Organism getOrganism() {
// return organism;
// }
//
// public boolean isSameOrganism(Cell c2) {
// return this.getOrganism().equals(c2.getOrganism());
// }
//
// }
// Path: src/com/sproutlife/model/step/lifemode/FriendlyLife.java
import java.util.Collection;
import com.sproutlife.model.GameModel;
import com.sproutlife.model.echosystem.Cell;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.step.lifemode;
public class FriendlyLife extends ParallelLife {
public FriendlyLife(GameModel gameModel) {
super(gameModel);
}
|
public boolean keepAlive(Cell c, Collection<Cell> neighbors, int x, int y) {
|
ShprAlex/SproutLife
|
src/com/sproutlife/Settings.java
|
// Path: src/com/sproutlife/model/seed/SeedFactory.java
// public static enum SeedType {
//
// L2_RPentomino ("L2 to R-Pentomino"),
// L2B1_RPentomino ("L2B1 to R-Pentomino"),
// Square2_RPentomino ("2x2 Box to R-Pentomino"),
// Glider_RPentomino ("Glider to R-Pentomino"),
// RPentomino_RPentomino ("R-Pentomino to R-Pentomino"),
// Boxlid_RPentomino ("Boxlid to R-Pentomino"),
// Boxlid3_RPentomino ("Boxlid3 to R-Pentomino"),
// Boxhat_RPentomino ("Boxhat to R-Pentomino"),
// Bentline1_RPentomino ("Bentline1 to R-Pentomino"),
// Bentline1_Plus ("Bentline1 to Plus"),
// Bentline1m_RPentomino ("Bentline1m to R-Pentomino"),
// Bentline_U3x3 ("Bentline to U 3x3"),
// BentlineMargin35_RPentomino ("BentlineM35 to R-Pentomino"),
// Onebit_RPentomino ("Onebit to R-Pentomino"),
// OnebitB1_RPentomino ("OnebitB1 to R-Pentomino"),
// Test_Pattern ("Test Pattern");
//
// private final String name;
//
// private SeedType(String name) {
// this.name = name;
// }
//
// public String toString() {
// return this.name;
// }
//
// public static SeedType get(String name) {
// for (SeedType st : SeedType.values()) {
// if (st.toString().equals(name)) {
// return st;
// }
// }
// return null;
// }
//
// /*
// * 8 way symmetry. Looks the same way under rotation and also mirroring.
// *
// * @return true if the seed has 8 way symmetry.
// */
// public boolean isSymmetric8() {
// switch (this) {
// case Square2_RPentomino:
// return true;
// case Onebit_RPentomino:
// return true;
// case OnebitB1_RPentomino:
// return true;
// // case Test_Pattern : return true;
// default:
// return false;
// }
// }
//
// /*
// * 4 way symmetry. Like a line which is symmetric under mirroring, and 2
// * rotations.
// *
// * @return true if the seed has 4 way symmetry.
// */
// public boolean isSymmetric4() {
// switch (this) {
// default:
// return false;
// }
// }
//
// /*
// * 2 way symmetry. All 4 rotations are different, but mirror images look
// * the same as a rotation
// *
// * @return true if the seed has 2 way symmetry.
// */
// public boolean isSymmetric2() {
// switch (this) {
// case L2_RPentomino:
// return true;
// case L2B1_RPentomino:
// return true;
// default:
// return false;
// }
// }
// }
|
import java.util.HashMap;
import com.sproutlife.model.seed.SeedFactory.SeedType;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife;
public class Settings {
HashMap<String, Object> settings;
public static String SEED_TYPE = "seedType";
public static String LIFE_MODE = "competitiveMode";
public static String MUTATION_ENABLED = "mutationEnabled";
public static String MUTATION_RATE = "mutationRate";
public static String MAX_LIFESPAN = "maxLifespan";
public static String TARGET_LIFESPAN = "targetLifespan";
public static String MIN_CHILDBEARING_AGE = "minAgeToHaveChildren";
public static String CHILD_TWO_PARENT_AGE = "childTwoParentAge";
public static String CHILD_THREE_PARENT_AGE = "childThreeParentAge";
//Determines whether seeds are sprouted immediately upon detection,
//Or a step later so seed cells can be displayed before the sprout is.
public static String SPROUT_DELAYED_MODE = "sproutDelayedMode";
public static String BACKGROUND_THEME = "backgroundTheme";
public static String COLOR_MODEL = "colorModel";
public static String AUTO_SPLIT_COLORS = "autoSplitColors";
public static String PRIMARY_HUE_DEGREES = "primaryHueDegrees";
public static String HUE_RANGE = "hueRange";
public Settings() {
settings = new HashMap<String, Object>();
initSettings();
}
public void initSettings() {
|
// Path: src/com/sproutlife/model/seed/SeedFactory.java
// public static enum SeedType {
//
// L2_RPentomino ("L2 to R-Pentomino"),
// L2B1_RPentomino ("L2B1 to R-Pentomino"),
// Square2_RPentomino ("2x2 Box to R-Pentomino"),
// Glider_RPentomino ("Glider to R-Pentomino"),
// RPentomino_RPentomino ("R-Pentomino to R-Pentomino"),
// Boxlid_RPentomino ("Boxlid to R-Pentomino"),
// Boxlid3_RPentomino ("Boxlid3 to R-Pentomino"),
// Boxhat_RPentomino ("Boxhat to R-Pentomino"),
// Bentline1_RPentomino ("Bentline1 to R-Pentomino"),
// Bentline1_Plus ("Bentline1 to Plus"),
// Bentline1m_RPentomino ("Bentline1m to R-Pentomino"),
// Bentline_U3x3 ("Bentline to U 3x3"),
// BentlineMargin35_RPentomino ("BentlineM35 to R-Pentomino"),
// Onebit_RPentomino ("Onebit to R-Pentomino"),
// OnebitB1_RPentomino ("OnebitB1 to R-Pentomino"),
// Test_Pattern ("Test Pattern");
//
// private final String name;
//
// private SeedType(String name) {
// this.name = name;
// }
//
// public String toString() {
// return this.name;
// }
//
// public static SeedType get(String name) {
// for (SeedType st : SeedType.values()) {
// if (st.toString().equals(name)) {
// return st;
// }
// }
// return null;
// }
//
// /*
// * 8 way symmetry. Looks the same way under rotation and also mirroring.
// *
// * @return true if the seed has 8 way symmetry.
// */
// public boolean isSymmetric8() {
// switch (this) {
// case Square2_RPentomino:
// return true;
// case Onebit_RPentomino:
// return true;
// case OnebitB1_RPentomino:
// return true;
// // case Test_Pattern : return true;
// default:
// return false;
// }
// }
//
// /*
// * 4 way symmetry. Like a line which is symmetric under mirroring, and 2
// * rotations.
// *
// * @return true if the seed has 4 way symmetry.
// */
// public boolean isSymmetric4() {
// switch (this) {
// default:
// return false;
// }
// }
//
// /*
// * 2 way symmetry. All 4 rotations are different, but mirror images look
// * the same as a rotation
// *
// * @return true if the seed has 2 way symmetry.
// */
// public boolean isSymmetric2() {
// switch (this) {
// case L2_RPentomino:
// return true;
// case L2B1_RPentomino:
// return true;
// default:
// return false;
// }
// }
// }
// Path: src/com/sproutlife/Settings.java
import java.util.HashMap;
import com.sproutlife.model.seed.SeedFactory.SeedType;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife;
public class Settings {
HashMap<String, Object> settings;
public static String SEED_TYPE = "seedType";
public static String LIFE_MODE = "competitiveMode";
public static String MUTATION_ENABLED = "mutationEnabled";
public static String MUTATION_RATE = "mutationRate";
public static String MAX_LIFESPAN = "maxLifespan";
public static String TARGET_LIFESPAN = "targetLifespan";
public static String MIN_CHILDBEARING_AGE = "minAgeToHaveChildren";
public static String CHILD_TWO_PARENT_AGE = "childTwoParentAge";
public static String CHILD_THREE_PARENT_AGE = "childThreeParentAge";
//Determines whether seeds are sprouted immediately upon detection,
//Or a step later so seed cells can be displayed before the sprout is.
public static String SPROUT_DELAYED_MODE = "sproutDelayedMode";
public static String BACKGROUND_THEME = "backgroundTheme";
public static String COLOR_MODEL = "colorModel";
public static String AUTO_SPLIT_COLORS = "autoSplitColors";
public static String PRIMARY_HUE_DEGREES = "primaryHueDegrees";
public static String HUE_RANGE = "hueRange";
public Settings() {
settings = new HashMap<String, Object>();
initSettings();
}
public void initSettings() {
|
set(Settings.SEED_TYPE, SeedType.Bentline1_RPentomino.toString());
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/L2B1RpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class L2B1RpPattern extends SeedSproutPattern {
public L2B1RpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/L2B1RpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class L2B1RpPattern extends SeedSproutPattern {
public L2B1RpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/BentlineU3x3.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class BentlineU3x3 extends SeedSproutPattern {
public BentlineU3x3() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/BentlineU3x3.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class BentlineU3x3 extends SeedSproutPattern {
public BentlineU3x3() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/panel/BoardSizeHandler.java
|
// Path: src/com/sproutlife/model/utils/EchosystemUtils.java
// public class EchosystemUtils {
//
// public static void updateBoardBounds(Echosystem echosystem, Rectangle bounds) {
// echosystem.getBoard().setSize(new Dimension(bounds.width, bounds.height));
//
// echosystem.getBoard().resetBoard();
//
// ArrayList<Cell> removeList = new ArrayList<Cell>(0);
//
// for (Organism o : echosystem.getOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// for (Cell current : o.getCells()) {
// if (current.x < bounds.x || current.x >= echosystem.getBoard().getWidth()+bounds.x
// || current.y < bounds.y || current.y >= echosystem.getBoard().getHeight()+bounds.y) {
// removeList.add(current);
// }
// else {
// Point cl = current.getLocation();
// current.setLocation(new Point(cl.x-bounds.x, cl.y-bounds.y));
// echosystem.getBoard().setCell(current);
// }
// }
// }
// for (Organism o : echosystem.getRetiredOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// }
// for (Cell r : removeList) {
// echosystem.removeCell(r, true);
// }
// pruneEmptyOrganisms(echosystem);
// }
//
// /*
// * Make sure the all cells on the board are contained within organisms, and
// * that all cells in organisms are on the board.
// *
// * @return if the board isn't consistent with organisms, return false
// */
// public static boolean validateBoard(Echosystem echosystem) {
// for (Organism o : echosystem.getOrganisms()) {
// for (Cell current : o.getCells()) {
// if (echosystem.getBoard().getCell(current.x, current.y) != current) {
// return false;
// }
// }
// }
// for (int i = 0; i < echosystem.getBoard().getWidth(); i++) {
// for (int j = 0; j < echosystem.getBoard().getHeight(); j++) {
// Cell c = echosystem.getBoard().getCell(i, j);
// if (c != null && c.getOrganism().getCell(c.x, c.y) != c) {
// return false;
// }
//
// }
// }
//
// return true;
// }
//
// public static void pruneEmptyOrganisms(Echosystem echosystem) {
// HashSet<Organism> pruneOrgs = new HashSet<Organism>();
// pruneOrgs.addAll(echosystem.getOrganisms());
// for (Organism org : pruneOrgs) {
// if (org.getCells().size() == 0) {
// echosystem.retireOrganism(org);
// }
// }
// }
// }
//
// Path: src/com/sproutlife/panel/gamepanel/ScrollPanel.java
// public interface ViewportResizedListener {
// public void viewportResized(int viewportWidth, int viewportHeight);
// }
//
// Path: src/com/sproutlife/renderer/Dimension2Double.java
// public class Dimension2Double extends Dimension2D {
// private double width;
// private double height;
//
// public Dimension2Double(double width, double height) {
// setSize(width, height);
// }
//
// @Override
// public double getWidth() {
// return width;
// }
//
// @Override
// public double getHeight() {
// return height;
// }
//
// @Override
// public void setSize(double width, double height) {
// this.width = width;
// this.height = height;
// }
//
// }
|
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Rectangle2D;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.sproutlife.model.utils.EchosystemUtils;
import com.sproutlife.panel.gamepanel.ScrollPanel.ViewportResizedListener;
import com.sproutlife.renderer.Dimension2Double;
|
package com.sproutlife.panel;
public class BoardSizeHandler {
PanelController pc;
boolean updatingSize = false;
ChangeListener boardSizeSpinnerListener;
ChangeListener imageSizeSpinnerListener;
public BoardSizeHandler(PanelController panelController) {
this.pc = panelController;
}
public void addListeners() {
boardSizeSpinnerListener = new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
pc.getDisplayControlPanel().getAutoSizeGridCheckbox().setSelected(false);
int width = (int) pc.getDisplayControlPanel().getBoardWidthSpinner().getValue();
int height = (int) pc.getDisplayControlPanel().getBoardHeightSpinner().getValue();
updateBoardSize(width, height);
}
};
imageSizeSpinnerListener = new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
pc.getDisplayControlPanel().getAutoSizeGridCheckbox().setSelected(false);
int width = (int) pc.getDisplayControlPanel().getImageWidthSpinner().getValue();
int height = (int) pc.getDisplayControlPanel().getImageHeightSpinner().getValue();
updateBoardSizeFromImageSize(new Dimension(width, height));
}
};
|
// Path: src/com/sproutlife/model/utils/EchosystemUtils.java
// public class EchosystemUtils {
//
// public static void updateBoardBounds(Echosystem echosystem, Rectangle bounds) {
// echosystem.getBoard().setSize(new Dimension(bounds.width, bounds.height));
//
// echosystem.getBoard().resetBoard();
//
// ArrayList<Cell> removeList = new ArrayList<Cell>(0);
//
// for (Organism o : echosystem.getOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// for (Cell current : o.getCells()) {
// if (current.x < bounds.x || current.x >= echosystem.getBoard().getWidth()+bounds.x
// || current.y < bounds.y || current.y >= echosystem.getBoard().getHeight()+bounds.y) {
// removeList.add(current);
// }
// else {
// Point cl = current.getLocation();
// current.setLocation(new Point(cl.x-bounds.x, cl.y-bounds.y));
// echosystem.getBoard().setCell(current);
// }
// }
// }
// for (Organism o : echosystem.getRetiredOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// }
// for (Cell r : removeList) {
// echosystem.removeCell(r, true);
// }
// pruneEmptyOrganisms(echosystem);
// }
//
// /*
// * Make sure the all cells on the board are contained within organisms, and
// * that all cells in organisms are on the board.
// *
// * @return if the board isn't consistent with organisms, return false
// */
// public static boolean validateBoard(Echosystem echosystem) {
// for (Organism o : echosystem.getOrganisms()) {
// for (Cell current : o.getCells()) {
// if (echosystem.getBoard().getCell(current.x, current.y) != current) {
// return false;
// }
// }
// }
// for (int i = 0; i < echosystem.getBoard().getWidth(); i++) {
// for (int j = 0; j < echosystem.getBoard().getHeight(); j++) {
// Cell c = echosystem.getBoard().getCell(i, j);
// if (c != null && c.getOrganism().getCell(c.x, c.y) != c) {
// return false;
// }
//
// }
// }
//
// return true;
// }
//
// public static void pruneEmptyOrganisms(Echosystem echosystem) {
// HashSet<Organism> pruneOrgs = new HashSet<Organism>();
// pruneOrgs.addAll(echosystem.getOrganisms());
// for (Organism org : pruneOrgs) {
// if (org.getCells().size() == 0) {
// echosystem.retireOrganism(org);
// }
// }
// }
// }
//
// Path: src/com/sproutlife/panel/gamepanel/ScrollPanel.java
// public interface ViewportResizedListener {
// public void viewportResized(int viewportWidth, int viewportHeight);
// }
//
// Path: src/com/sproutlife/renderer/Dimension2Double.java
// public class Dimension2Double extends Dimension2D {
// private double width;
// private double height;
//
// public Dimension2Double(double width, double height) {
// setSize(width, height);
// }
//
// @Override
// public double getWidth() {
// return width;
// }
//
// @Override
// public double getHeight() {
// return height;
// }
//
// @Override
// public void setSize(double width, double height) {
// this.width = width;
// this.height = height;
// }
//
// }
// Path: src/com/sproutlife/panel/BoardSizeHandler.java
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Rectangle2D;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.sproutlife.model.utils.EchosystemUtils;
import com.sproutlife.panel.gamepanel.ScrollPanel.ViewportResizedListener;
import com.sproutlife.renderer.Dimension2Double;
package com.sproutlife.panel;
public class BoardSizeHandler {
PanelController pc;
boolean updatingSize = false;
ChangeListener boardSizeSpinnerListener;
ChangeListener imageSizeSpinnerListener;
public BoardSizeHandler(PanelController panelController) {
this.pc = panelController;
}
public void addListeners() {
boardSizeSpinnerListener = new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
pc.getDisplayControlPanel().getAutoSizeGridCheckbox().setSelected(false);
int width = (int) pc.getDisplayControlPanel().getBoardWidthSpinner().getValue();
int height = (int) pc.getDisplayControlPanel().getBoardHeightSpinner().getValue();
updateBoardSize(width, height);
}
};
imageSizeSpinnerListener = new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
pc.getDisplayControlPanel().getAutoSizeGridCheckbox().setSelected(false);
int width = (int) pc.getDisplayControlPanel().getImageWidthSpinner().getValue();
int height = (int) pc.getDisplayControlPanel().getImageHeightSpinner().getValue();
updateBoardSizeFromImageSize(new Dimension(width, height));
}
};
|
pc.getScrollPanel().addViewportResizedListener(new ViewportResizedListener() {
|
ShprAlex/SproutLife
|
src/com/sproutlife/panel/BoardSizeHandler.java
|
// Path: src/com/sproutlife/model/utils/EchosystemUtils.java
// public class EchosystemUtils {
//
// public static void updateBoardBounds(Echosystem echosystem, Rectangle bounds) {
// echosystem.getBoard().setSize(new Dimension(bounds.width, bounds.height));
//
// echosystem.getBoard().resetBoard();
//
// ArrayList<Cell> removeList = new ArrayList<Cell>(0);
//
// for (Organism o : echosystem.getOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// for (Cell current : o.getCells()) {
// if (current.x < bounds.x || current.x >= echosystem.getBoard().getWidth()+bounds.x
// || current.y < bounds.y || current.y >= echosystem.getBoard().getHeight()+bounds.y) {
// removeList.add(current);
// }
// else {
// Point cl = current.getLocation();
// current.setLocation(new Point(cl.x-bounds.x, cl.y-bounds.y));
// echosystem.getBoard().setCell(current);
// }
// }
// }
// for (Organism o : echosystem.getRetiredOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// }
// for (Cell r : removeList) {
// echosystem.removeCell(r, true);
// }
// pruneEmptyOrganisms(echosystem);
// }
//
// /*
// * Make sure the all cells on the board are contained within organisms, and
// * that all cells in organisms are on the board.
// *
// * @return if the board isn't consistent with organisms, return false
// */
// public static boolean validateBoard(Echosystem echosystem) {
// for (Organism o : echosystem.getOrganisms()) {
// for (Cell current : o.getCells()) {
// if (echosystem.getBoard().getCell(current.x, current.y) != current) {
// return false;
// }
// }
// }
// for (int i = 0; i < echosystem.getBoard().getWidth(); i++) {
// for (int j = 0; j < echosystem.getBoard().getHeight(); j++) {
// Cell c = echosystem.getBoard().getCell(i, j);
// if (c != null && c.getOrganism().getCell(c.x, c.y) != c) {
// return false;
// }
//
// }
// }
//
// return true;
// }
//
// public static void pruneEmptyOrganisms(Echosystem echosystem) {
// HashSet<Organism> pruneOrgs = new HashSet<Organism>();
// pruneOrgs.addAll(echosystem.getOrganisms());
// for (Organism org : pruneOrgs) {
// if (org.getCells().size() == 0) {
// echosystem.retireOrganism(org);
// }
// }
// }
// }
//
// Path: src/com/sproutlife/panel/gamepanel/ScrollPanel.java
// public interface ViewportResizedListener {
// public void viewportResized(int viewportWidth, int viewportHeight);
// }
//
// Path: src/com/sproutlife/renderer/Dimension2Double.java
// public class Dimension2Double extends Dimension2D {
// private double width;
// private double height;
//
// public Dimension2Double(double width, double height) {
// setSize(width, height);
// }
//
// @Override
// public double getWidth() {
// return width;
// }
//
// @Override
// public double getHeight() {
// return height;
// }
//
// @Override
// public void setSize(double width, double height) {
// this.width = width;
// this.height = height;
// }
//
// }
|
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Rectangle2D;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.sproutlife.model.utils.EchosystemUtils;
import com.sproutlife.panel.gamepanel.ScrollPanel.ViewportResizedListener;
import com.sproutlife.renderer.Dimension2Double;
|
pc.getDisplayControlPanel().getAutoSizeGridCheckbox().addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(pc.getDisplayControlPanel().getAutoSizeGridCheckbox().isSelected()) {
clipToView();
}
}
});
}
public void updateBoardSizeFromImageSize(Dimension d) {
updateBoardSizeFromImageSize(new Rectangle(0, 0, d.width,d.height));
}
public void updateBoardSizeFromImageSize(Rectangle r) {
if (updatingSize) {
return;
}
updatingSize = true;
pc.getInteractionLock().writeLock().lock();
double zoom = pc.getBoardRenderer().getZoom();
double blockSize = pc.getBoardRenderer().getBlockSize();
int boardWidth = (int)((r.width/zoom-40)/blockSize);
int boardHeight = (int)((r.height/zoom-50)/blockSize);
int x = (int)(r.x/blockSize/zoom);
int y = (int)(r.y/blockSize/zoom);
boardWidth=Math.max(1, boardWidth);
boardHeight=Math.max(1, boardHeight);
|
// Path: src/com/sproutlife/model/utils/EchosystemUtils.java
// public class EchosystemUtils {
//
// public static void updateBoardBounds(Echosystem echosystem, Rectangle bounds) {
// echosystem.getBoard().setSize(new Dimension(bounds.width, bounds.height));
//
// echosystem.getBoard().resetBoard();
//
// ArrayList<Cell> removeList = new ArrayList<Cell>(0);
//
// for (Organism o : echosystem.getOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// for (Cell current : o.getCells()) {
// if (current.x < bounds.x || current.x >= echosystem.getBoard().getWidth()+bounds.x
// || current.y < bounds.y || current.y >= echosystem.getBoard().getHeight()+bounds.y) {
// removeList.add(current);
// }
// else {
// Point cl = current.getLocation();
// current.setLocation(new Point(cl.x-bounds.x, cl.y-bounds.y));
// echosystem.getBoard().setCell(current);
// }
// }
// }
// for (Organism o : echosystem.getRetiredOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// }
// for (Cell r : removeList) {
// echosystem.removeCell(r, true);
// }
// pruneEmptyOrganisms(echosystem);
// }
//
// /*
// * Make sure the all cells on the board are contained within organisms, and
// * that all cells in organisms are on the board.
// *
// * @return if the board isn't consistent with organisms, return false
// */
// public static boolean validateBoard(Echosystem echosystem) {
// for (Organism o : echosystem.getOrganisms()) {
// for (Cell current : o.getCells()) {
// if (echosystem.getBoard().getCell(current.x, current.y) != current) {
// return false;
// }
// }
// }
// for (int i = 0; i < echosystem.getBoard().getWidth(); i++) {
// for (int j = 0; j < echosystem.getBoard().getHeight(); j++) {
// Cell c = echosystem.getBoard().getCell(i, j);
// if (c != null && c.getOrganism().getCell(c.x, c.y) != c) {
// return false;
// }
//
// }
// }
//
// return true;
// }
//
// public static void pruneEmptyOrganisms(Echosystem echosystem) {
// HashSet<Organism> pruneOrgs = new HashSet<Organism>();
// pruneOrgs.addAll(echosystem.getOrganisms());
// for (Organism org : pruneOrgs) {
// if (org.getCells().size() == 0) {
// echosystem.retireOrganism(org);
// }
// }
// }
// }
//
// Path: src/com/sproutlife/panel/gamepanel/ScrollPanel.java
// public interface ViewportResizedListener {
// public void viewportResized(int viewportWidth, int viewportHeight);
// }
//
// Path: src/com/sproutlife/renderer/Dimension2Double.java
// public class Dimension2Double extends Dimension2D {
// private double width;
// private double height;
//
// public Dimension2Double(double width, double height) {
// setSize(width, height);
// }
//
// @Override
// public double getWidth() {
// return width;
// }
//
// @Override
// public double getHeight() {
// return height;
// }
//
// @Override
// public void setSize(double width, double height) {
// this.width = width;
// this.height = height;
// }
//
// }
// Path: src/com/sproutlife/panel/BoardSizeHandler.java
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Rectangle2D;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.sproutlife.model.utils.EchosystemUtils;
import com.sproutlife.panel.gamepanel.ScrollPanel.ViewportResizedListener;
import com.sproutlife.renderer.Dimension2Double;
pc.getDisplayControlPanel().getAutoSizeGridCheckbox().addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(pc.getDisplayControlPanel().getAutoSizeGridCheckbox().isSelected()) {
clipToView();
}
}
});
}
public void updateBoardSizeFromImageSize(Dimension d) {
updateBoardSizeFromImageSize(new Rectangle(0, 0, d.width,d.height));
}
public void updateBoardSizeFromImageSize(Rectangle r) {
if (updatingSize) {
return;
}
updatingSize = true;
pc.getInteractionLock().writeLock().lock();
double zoom = pc.getBoardRenderer().getZoom();
double blockSize = pc.getBoardRenderer().getBlockSize();
int boardWidth = (int)((r.width/zoom-40)/blockSize);
int boardHeight = (int)((r.height/zoom-50)/blockSize);
int x = (int)(r.x/blockSize/zoom);
int y = (int)(r.y/blockSize/zoom);
boardWidth=Math.max(1, boardWidth);
boardHeight=Math.max(1, boardHeight);
|
EchosystemUtils.updateBoardBounds(pc.getGameModel().getEchosystem(), new Rectangle(x,y,boardWidth, boardHeight));
|
ShprAlex/SproutLife
|
src/com/sproutlife/panel/BoardSizeHandler.java
|
// Path: src/com/sproutlife/model/utils/EchosystemUtils.java
// public class EchosystemUtils {
//
// public static void updateBoardBounds(Echosystem echosystem, Rectangle bounds) {
// echosystem.getBoard().setSize(new Dimension(bounds.width, bounds.height));
//
// echosystem.getBoard().resetBoard();
//
// ArrayList<Cell> removeList = new ArrayList<Cell>(0);
//
// for (Organism o : echosystem.getOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// for (Cell current : o.getCells()) {
// if (current.x < bounds.x || current.x >= echosystem.getBoard().getWidth()+bounds.x
// || current.y < bounds.y || current.y >= echosystem.getBoard().getHeight()+bounds.y) {
// removeList.add(current);
// }
// else {
// Point cl = current.getLocation();
// current.setLocation(new Point(cl.x-bounds.x, cl.y-bounds.y));
// echosystem.getBoard().setCell(current);
// }
// }
// }
// for (Organism o : echosystem.getRetiredOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// }
// for (Cell r : removeList) {
// echosystem.removeCell(r, true);
// }
// pruneEmptyOrganisms(echosystem);
// }
//
// /*
// * Make sure the all cells on the board are contained within organisms, and
// * that all cells in organisms are on the board.
// *
// * @return if the board isn't consistent with organisms, return false
// */
// public static boolean validateBoard(Echosystem echosystem) {
// for (Organism o : echosystem.getOrganisms()) {
// for (Cell current : o.getCells()) {
// if (echosystem.getBoard().getCell(current.x, current.y) != current) {
// return false;
// }
// }
// }
// for (int i = 0; i < echosystem.getBoard().getWidth(); i++) {
// for (int j = 0; j < echosystem.getBoard().getHeight(); j++) {
// Cell c = echosystem.getBoard().getCell(i, j);
// if (c != null && c.getOrganism().getCell(c.x, c.y) != c) {
// return false;
// }
//
// }
// }
//
// return true;
// }
//
// public static void pruneEmptyOrganisms(Echosystem echosystem) {
// HashSet<Organism> pruneOrgs = new HashSet<Organism>();
// pruneOrgs.addAll(echosystem.getOrganisms());
// for (Organism org : pruneOrgs) {
// if (org.getCells().size() == 0) {
// echosystem.retireOrganism(org);
// }
// }
// }
// }
//
// Path: src/com/sproutlife/panel/gamepanel/ScrollPanel.java
// public interface ViewportResizedListener {
// public void viewportResized(int viewportWidth, int viewportHeight);
// }
//
// Path: src/com/sproutlife/renderer/Dimension2Double.java
// public class Dimension2Double extends Dimension2D {
// private double width;
// private double height;
//
// public Dimension2Double(double width, double height) {
// setSize(width, height);
// }
//
// @Override
// public double getWidth() {
// return width;
// }
//
// @Override
// public double getHeight() {
// return height;
// }
//
// @Override
// public void setSize(double width, double height) {
// this.width = width;
// this.height = height;
// }
//
// }
|
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Rectangle2D;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.sproutlife.model.utils.EchosystemUtils;
import com.sproutlife.panel.gamepanel.ScrollPanel.ViewportResizedListener;
import com.sproutlife.renderer.Dimension2Double;
|
public void itemStateChanged(ItemEvent e) {
if(pc.getDisplayControlPanel().getAutoSizeGridCheckbox().isSelected()) {
clipToView();
}
}
});
}
public void updateBoardSizeFromImageSize(Dimension d) {
updateBoardSizeFromImageSize(new Rectangle(0, 0, d.width,d.height));
}
public void updateBoardSizeFromImageSize(Rectangle r) {
if (updatingSize) {
return;
}
updatingSize = true;
pc.getInteractionLock().writeLock().lock();
double zoom = pc.getBoardRenderer().getZoom();
double blockSize = pc.getBoardRenderer().getBlockSize();
int boardWidth = (int)((r.width/zoom-40)/blockSize);
int boardHeight = (int)((r.height/zoom-50)/blockSize);
int x = (int)(r.x/blockSize/zoom);
int y = (int)(r.y/blockSize/zoom);
boardWidth=Math.max(1, boardWidth);
boardHeight=Math.max(1, boardHeight);
EchosystemUtils.updateBoardBounds(pc.getGameModel().getEchosystem(), new Rectangle(x,y,boardWidth, boardHeight));
|
// Path: src/com/sproutlife/model/utils/EchosystemUtils.java
// public class EchosystemUtils {
//
// public static void updateBoardBounds(Echosystem echosystem, Rectangle bounds) {
// echosystem.getBoard().setSize(new Dimension(bounds.width, bounds.height));
//
// echosystem.getBoard().resetBoard();
//
// ArrayList<Cell> removeList = new ArrayList<Cell>(0);
//
// for (Organism o : echosystem.getOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// for (Cell current : o.getCells()) {
// if (current.x < bounds.x || current.x >= echosystem.getBoard().getWidth()+bounds.x
// || current.y < bounds.y || current.y >= echosystem.getBoard().getHeight()+bounds.y) {
// removeList.add(current);
// }
// else {
// Point cl = current.getLocation();
// current.setLocation(new Point(cl.x-bounds.x, cl.y-bounds.y));
// echosystem.getBoard().setCell(current);
// }
// }
// }
// for (Organism o : echosystem.getRetiredOrganisms()) {
// Point ol = o.getLocation();
// o.setLocation(ol.x-bounds.x , ol.y-bounds.y);
// }
// for (Cell r : removeList) {
// echosystem.removeCell(r, true);
// }
// pruneEmptyOrganisms(echosystem);
// }
//
// /*
// * Make sure the all cells on the board are contained within organisms, and
// * that all cells in organisms are on the board.
// *
// * @return if the board isn't consistent with organisms, return false
// */
// public static boolean validateBoard(Echosystem echosystem) {
// for (Organism o : echosystem.getOrganisms()) {
// for (Cell current : o.getCells()) {
// if (echosystem.getBoard().getCell(current.x, current.y) != current) {
// return false;
// }
// }
// }
// for (int i = 0; i < echosystem.getBoard().getWidth(); i++) {
// for (int j = 0; j < echosystem.getBoard().getHeight(); j++) {
// Cell c = echosystem.getBoard().getCell(i, j);
// if (c != null && c.getOrganism().getCell(c.x, c.y) != c) {
// return false;
// }
//
// }
// }
//
// return true;
// }
//
// public static void pruneEmptyOrganisms(Echosystem echosystem) {
// HashSet<Organism> pruneOrgs = new HashSet<Organism>();
// pruneOrgs.addAll(echosystem.getOrganisms());
// for (Organism org : pruneOrgs) {
// if (org.getCells().size() == 0) {
// echosystem.retireOrganism(org);
// }
// }
// }
// }
//
// Path: src/com/sproutlife/panel/gamepanel/ScrollPanel.java
// public interface ViewportResizedListener {
// public void viewportResized(int viewportWidth, int viewportHeight);
// }
//
// Path: src/com/sproutlife/renderer/Dimension2Double.java
// public class Dimension2Double extends Dimension2D {
// private double width;
// private double height;
//
// public Dimension2Double(double width, double height) {
// setSize(width, height);
// }
//
// @Override
// public double getWidth() {
// return width;
// }
//
// @Override
// public double getHeight() {
// return height;
// }
//
// @Override
// public void setSize(double width, double height) {
// this.width = width;
// this.height = height;
// }
//
// }
// Path: src/com/sproutlife/panel/BoardSizeHandler.java
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Rectangle2D;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.sproutlife.model.utils.EchosystemUtils;
import com.sproutlife.panel.gamepanel.ScrollPanel.ViewportResizedListener;
import com.sproutlife.renderer.Dimension2Double;
public void itemStateChanged(ItemEvent e) {
if(pc.getDisplayControlPanel().getAutoSizeGridCheckbox().isSelected()) {
clipToView();
}
}
});
}
public void updateBoardSizeFromImageSize(Dimension d) {
updateBoardSizeFromImageSize(new Rectangle(0, 0, d.width,d.height));
}
public void updateBoardSizeFromImageSize(Rectangle r) {
if (updatingSize) {
return;
}
updatingSize = true;
pc.getInteractionLock().writeLock().lock();
double zoom = pc.getBoardRenderer().getZoom();
double blockSize = pc.getBoardRenderer().getBlockSize();
int boardWidth = (int)((r.width/zoom-40)/blockSize);
int boardHeight = (int)((r.height/zoom-50)/blockSize);
int x = (int)(r.x/blockSize/zoom);
int y = (int)(r.y/blockSize/zoom);
boardWidth=Math.max(1, boardWidth);
boardHeight=Math.max(1, boardHeight);
EchosystemUtils.updateBoardBounds(pc.getGameModel().getEchosystem(), new Rectangle(x,y,boardWidth, boardHeight));
|
pc.getBoardRenderer().setBounds(new Dimension2Double(r.width/zoom, r.height/zoom));
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/BoxhatRpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class BoxhatRpPattern extends SeedSproutPattern {
public BoxhatRpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/BoxhatRpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class BoxhatRpPattern extends SeedSproutPattern {
public BoxhatRpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/step/GameStep.java
|
// Path: src/com/sproutlife/model/GameModel.java
// public class GameModel {
// private Echosystem echosystem;
// private GameClock clock;
// private GameStep gameStep;
// private GameThread gameThread;
// private Settings settings;
// private Stats stats;
//
// public GameModel(Settings settings, ReentrantReadWriteLock interactionLock) {
// this.settings = settings;
// this.clock = new GameClock();
// echosystem = new Echosystem(clock);
// gameStep = new GameStep(this);
// gameThread = new GameThread(this, interactionLock);
// stats = new Stats(this);
// }
//
// public Echosystem getEchosystem() {
// return echosystem;
// }
//
// public Board getBoard() {
// return echosystem.getBoard();
// }
//
// public int getTime() {
// return clock.getTime();
// }
//
// public Stats getStats() {
// return stats;
// }
//
// public Settings getSettings() {
// return settings;
// }
//
// public GameThread getGameThread() {
// return gameThread;
// }
//
// private GameClock getClock() {
// return clock;
// }
//
// private void incrementTime() {
// clock.increment();
// }
//
// public void performGameStep() {
// incrementTime();
// gameStep.perform();
// }
//
// public void resetGame() {
// getEchosystem().resetCells();
// EchosystemUtils.pruneEmptyOrganisms(getEchosystem());
// getEchosystem().clearRetiredOrgs();
// getStats().reset();
// getClock().reset();
// }
//
// public void setPlayGame(boolean playGame) {
// gameThread.setPlayGame(playGame);
// }
//
// public boolean isPlaying() {
// return gameThread.isPlaying();
// }
//
// public void setGameStepListener(GameStepListener l) {
// if (gameThread == null) {
// return;
// }
// gameThread.addGameStepListener(l);
// }
// }
|
import com.sproutlife.model.GameModel;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.step;
public class GameStep extends Step {
public static enum StepType {
GAME_STEP,
LIFE_STEP,
SPROUT_STEP,
MUTATION_STEP,
PRUNE_STEP,
COLOR_STEP,
STEP_BUNDLE
}
LifeStep lifeStep;
SproutStep sproutStep;
MutationStep mutationStep;
PreReproductionStep preReproductionStep;
RetireAndPruneStep retireAndPruneStep;
BattleColorStep colorsStep;
|
// Path: src/com/sproutlife/model/GameModel.java
// public class GameModel {
// private Echosystem echosystem;
// private GameClock clock;
// private GameStep gameStep;
// private GameThread gameThread;
// private Settings settings;
// private Stats stats;
//
// public GameModel(Settings settings, ReentrantReadWriteLock interactionLock) {
// this.settings = settings;
// this.clock = new GameClock();
// echosystem = new Echosystem(clock);
// gameStep = new GameStep(this);
// gameThread = new GameThread(this, interactionLock);
// stats = new Stats(this);
// }
//
// public Echosystem getEchosystem() {
// return echosystem;
// }
//
// public Board getBoard() {
// return echosystem.getBoard();
// }
//
// public int getTime() {
// return clock.getTime();
// }
//
// public Stats getStats() {
// return stats;
// }
//
// public Settings getSettings() {
// return settings;
// }
//
// public GameThread getGameThread() {
// return gameThread;
// }
//
// private GameClock getClock() {
// return clock;
// }
//
// private void incrementTime() {
// clock.increment();
// }
//
// public void performGameStep() {
// incrementTime();
// gameStep.perform();
// }
//
// public void resetGame() {
// getEchosystem().resetCells();
// EchosystemUtils.pruneEmptyOrganisms(getEchosystem());
// getEchosystem().clearRetiredOrgs();
// getStats().reset();
// getClock().reset();
// }
//
// public void setPlayGame(boolean playGame) {
// gameThread.setPlayGame(playGame);
// }
//
// public boolean isPlaying() {
// return gameThread.isPlaying();
// }
//
// public void setGameStepListener(GameStepListener l) {
// if (gameThread == null) {
// return;
// }
// gameThread.addGameStepListener(l);
// }
// }
// Path: src/com/sproutlife/model/step/GameStep.java
import com.sproutlife.model.GameModel;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.step;
public class GameStep extends Step {
public static enum StepType {
GAME_STEP,
LIFE_STEP,
SPROUT_STEP,
MUTATION_STEP,
PRUNE_STEP,
COLOR_STEP,
STEP_BUNDLE
}
LifeStep lifeStep;
SproutStep sproutStep;
MutationStep mutationStep;
PreReproductionStep preReproductionStep;
RetireAndPruneStep retireAndPruneStep;
BattleColorStep colorsStep;
|
public GameStep(GameModel gameModel) {
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/seed/patterns/Boxlid3RpPattern.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class Boxlid3RpPattern extends SeedSproutPattern {
public Boxlid3RpPattern() {
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
//
// Path: src/com/sproutlife/model/seed/SeedSproutPattern.java
// public class SeedSproutPattern {
//
// protected BitPattern seedPattern;
//
// protected BitPattern sproutPattern;
//
// protected Point sproutOffset;
//
// public BitPattern getSeedPattern() {
// return seedPattern;
// }
//
// public BitPattern getSproutPattern() {
// return sproutPattern;
// }
//
// public Point getSproutOffset() {
// return sproutOffset;
// }
// }
// Path: src/com/sproutlife/model/seed/patterns/Boxlid3RpPattern.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
public class Boxlid3RpPattern extends SeedSproutPattern {
public Boxlid3RpPattern() {
|
this.seedPattern = new BitPattern(new int[][]
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/rotations/Rotations.java
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
|
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.rotations;
/**
* @author Alex Shapiro
*
*/
public class Rotations {
private static Rotation[][] rotations = new Rotation[4][2];
public static Rotation get(int angle, boolean mirror) {
Rotation r = rotations[angle][mirror?0:1];
if (r==null) {
r = new Rotation(angle, mirror);
rotations[angle][mirror?0:1]=r;
}
return r;
}
public static Rotation get(int angle) {
return get(angle, false);
}
public static Rotation get() {
return get(0, false);
}
|
// Path: src/com/sproutlife/model/seed/BitPattern.java
// public class BitPattern {
//
// protected int[][] bitPattern;
//
// protected Point onBit = null;
//
// public BitPattern() {
//
// }
//
// public BitPattern(int[][] bitPattern) {
// this.bitPattern = bitPattern;
// }
//
// public BitPattern(int[][] bitPattern, boolean xySwitch) {
//
// if (xySwitch) {
// this.bitPattern = xySwitch(bitPattern);
// }
// else {
// this.bitPattern = bitPattern;
// }
//
// }
//
// public int getWidth() {
// return bitPattern.length;
// }
//
// public int getWidth(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getWidth();
// }
// return getHeight();
// }
//
// public int getHeight() {
// return bitPattern[0].length;
// }
//
// public int getHeight(Rotation r) {
// if (r.getAngle()==0 || r.getAngle()==2) {
// return getHeight();
// }
// return getWidth();
// }
//
// boolean getBit(int x, int y) {
// return bitPattern[x][y]==1;
// }
//
// boolean getBit(int x, int y, Rotation r) {
// Point rp = Rotations.fromBoard(new Point(x,y), this, r);
// return getBit(rp.x, rp.y);
// }
//
// public Point getCenter() {
// return new Point((getWidth()-1)/2,(getHeight()-1)/2);
// }
//
// public Point getCenter(Rotation r) {
// return Rotations.toBoard(getCenter(), this, r);
// }
//
// public Point getOnBit() {
//
// if (this.onBit!=null) {
// return this.onBit;
// }
// else {
// for (int x=0;x<getWidth();x++) {
// for (int y=0;y<getHeight();y++) {
// if (getBit(x,y)) {
// this.onBit = new Point(x,y);
// return onBit;
// }
// }
// }
// }
// return null;
// }
//
// public Point getOnBit(Rotation r) {
// return Rotations.toBoard(getOnBit(), this, r);
// }
//
// public static int[][] xySwitch(int[][] shape) {
// if (shape.length==0) {
// return new int[0][0];
// }
// int[][] newShape = new int[shape[0].length][shape.length];
//
// for (int i=0;i<shape.length;i++) {
// for (int j=0;j<shape[0].length;j++) {
// newShape[j][i] = shape[i][j];
// }
// }
//
// return newShape;
//
// }
// }
// Path: src/com/sproutlife/model/rotations/Rotations.java
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.rotations;
/**
* @author Alex Shapiro
*
*/
public class Rotations {
private static Rotation[][] rotations = new Rotation[4][2];
public static Rotation get(int angle, boolean mirror) {
Rotation r = rotations[angle][mirror?0:1];
if (r==null) {
r = new Rotation(angle, mirror);
rotations[angle][mirror?0:1]=r;
}
return r;
}
public static Rotation get(int angle) {
return get(angle, false);
}
public static Rotation get() {
return get(0, false);
}
|
public static Point fromBoard(Point point, BitPattern bp1, Rotation r) {
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/echosystem/Echosystem.java
|
// Path: src/com/sproutlife/model/GameClock.java
// public class GameClock {
// private int time;
//
// public GameClock() {
// time = 0;
// }
//
// public int getTime() {
// return time;
// }
//
// void increment() {
// time++;
// }
//
// void reset() {
// this.time = 0;
// }
// }
//
// Path: src/com/sproutlife/model/seed/Seed.java
// public class Seed {
//
// protected SeedSproutPattern pattern;
// public Point position = null;
// public Rotation rotation;
// public int seedBorder = 1;
// public Point parentPosition;
// //Organism organism;
//
// public Seed(SeedSproutPattern pattern, Rotation r) {
// this.pattern = pattern;
// this.rotation = r;
// }
//
// public Seed(SeedSproutPattern pattern) {
// this(pattern, Rotations.get());
// }
//
// public Rotation getRotation() {
// return rotation;
// }
//
// public Point getPosition() {
// return position;
// }
//
// public void setPosition(int x, int y) {
// this.position = new Point(x,y);
// }
//
// public int getSeedBorder() {
// return seedBorder;
// }
//
// public void setSeedBorder(int b) {
// this.seedBorder = b;
// }
//
// public Point getParentPosition() {
// return parentPosition;
// }
//
// public void setParentPosition(Point parentPosition) {
// this.parentPosition = parentPosition;
// }
// /*
// public Organism getOrganism() {
// return organism;
// }
//
// public void setOrganism(Organism organism) {
// this.organism = organism;
// }
// */
//
// public SeedSproutPattern getSeedSproutPattern() {
// return pattern;
// }
//
// public BitPattern getSeedPattern() {
// return pattern.getSeedPattern();
// }
//
// public BitPattern getSproutPattern() {
// return pattern.getSproutPattern();
// }
//
// public boolean getSeedBit(int x, int y) {
// return getSeedPattern().getBit(x, y, getRotation());
// }
//
// public boolean getSproutBit(int x, int y) {
// return getSproutPattern().getBit(x, y, getRotation());
// }
//
// public int getSeedWidth() {
// return getSeedPattern().getWidth(getRotation());
// }
//
// public int getSeedHeight() {
// return getSeedPattern().getHeight(getRotation());
// }
//
// public int getSproutWidth() {
// return getSproutPattern().getWidth(getRotation());
// }
//
// public int getSproutHeight() {
// return getSproutPattern().getHeight(getRotation());
// }
//
// public Point getSproutOffset() {
// return Rotations.offsetToBoard(
// pattern.getSproutOffset(),
// getSeedPattern(),
// getSproutPattern(),
// getRotation());
// }
//
// public Point getSproutPosition() {
// Point sproutOffset = getSproutOffset();
// return new Point(position.x + sproutOffset.x, position.y + sproutOffset.y);
// }
//
// public Point getSproutCenter() {
// Point sproutPosition = getSproutPosition();
// Point sproutCenter = getSproutPattern().getCenter(getRotation());
//
// int ssX = sproutPosition.x+sproutCenter.x;
// int ssY = sproutPosition.y+sproutCenter.y;
//
// return new Point(ssX, ssY);
// }
//
// public Point getSeedOnBit() {
// return pattern.getSeedPattern().getOnBit(getRotation());
// }
//
// public Point getSeedOnPosition() {
// Point pos = this.getPosition();
// Point onOffset = this.getSeedOnBit();
// return new Point(pos.x+onOffset.x,pos.y+onOffset.y);
// }
// }
|
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import com.sproutlife.model.GameClock;
import com.sproutlife.model.seed.Seed;
|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.echosystem;
/**
* The Echosystem keeps track of all our organisms, living and recently retired.
* It also manages the Board.
*
* @author Alex Shapiro
*/
public class Echosystem {
List<Organism> organisms;
Deque<Organism> retiredOrganisms;
Board board;
int defaultOrgLifespan;
int retirementTimeSpan;
|
// Path: src/com/sproutlife/model/GameClock.java
// public class GameClock {
// private int time;
//
// public GameClock() {
// time = 0;
// }
//
// public int getTime() {
// return time;
// }
//
// void increment() {
// time++;
// }
//
// void reset() {
// this.time = 0;
// }
// }
//
// Path: src/com/sproutlife/model/seed/Seed.java
// public class Seed {
//
// protected SeedSproutPattern pattern;
// public Point position = null;
// public Rotation rotation;
// public int seedBorder = 1;
// public Point parentPosition;
// //Organism organism;
//
// public Seed(SeedSproutPattern pattern, Rotation r) {
// this.pattern = pattern;
// this.rotation = r;
// }
//
// public Seed(SeedSproutPattern pattern) {
// this(pattern, Rotations.get());
// }
//
// public Rotation getRotation() {
// return rotation;
// }
//
// public Point getPosition() {
// return position;
// }
//
// public void setPosition(int x, int y) {
// this.position = new Point(x,y);
// }
//
// public int getSeedBorder() {
// return seedBorder;
// }
//
// public void setSeedBorder(int b) {
// this.seedBorder = b;
// }
//
// public Point getParentPosition() {
// return parentPosition;
// }
//
// public void setParentPosition(Point parentPosition) {
// this.parentPosition = parentPosition;
// }
// /*
// public Organism getOrganism() {
// return organism;
// }
//
// public void setOrganism(Organism organism) {
// this.organism = organism;
// }
// */
//
// public SeedSproutPattern getSeedSproutPattern() {
// return pattern;
// }
//
// public BitPattern getSeedPattern() {
// return pattern.getSeedPattern();
// }
//
// public BitPattern getSproutPattern() {
// return pattern.getSproutPattern();
// }
//
// public boolean getSeedBit(int x, int y) {
// return getSeedPattern().getBit(x, y, getRotation());
// }
//
// public boolean getSproutBit(int x, int y) {
// return getSproutPattern().getBit(x, y, getRotation());
// }
//
// public int getSeedWidth() {
// return getSeedPattern().getWidth(getRotation());
// }
//
// public int getSeedHeight() {
// return getSeedPattern().getHeight(getRotation());
// }
//
// public int getSproutWidth() {
// return getSproutPattern().getWidth(getRotation());
// }
//
// public int getSproutHeight() {
// return getSproutPattern().getHeight(getRotation());
// }
//
// public Point getSproutOffset() {
// return Rotations.offsetToBoard(
// pattern.getSproutOffset(),
// getSeedPattern(),
// getSproutPattern(),
// getRotation());
// }
//
// public Point getSproutPosition() {
// Point sproutOffset = getSproutOffset();
// return new Point(position.x + sproutOffset.x, position.y + sproutOffset.y);
// }
//
// public Point getSproutCenter() {
// Point sproutPosition = getSproutPosition();
// Point sproutCenter = getSproutPattern().getCenter(getRotation());
//
// int ssX = sproutPosition.x+sproutCenter.x;
// int ssY = sproutPosition.y+sproutCenter.y;
//
// return new Point(ssX, ssY);
// }
//
// public Point getSeedOnBit() {
// return pattern.getSeedPattern().getOnBit(getRotation());
// }
//
// public Point getSeedOnPosition() {
// Point pos = this.getPosition();
// Point onOffset = this.getSeedOnBit();
// return new Point(pos.x+onOffset.x,pos.y+onOffset.y);
// }
// }
// Path: src/com/sproutlife/model/echosystem/Echosystem.java
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import com.sproutlife.model.GameClock;
import com.sproutlife.model.seed.Seed;
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.echosystem;
/**
* The Echosystem keeps track of all our organisms, living and recently retired.
* It also manages the Board.
*
* @author Alex Shapiro
*/
public class Echosystem {
List<Organism> organisms;
Deque<Organism> retiredOrganisms;
Board board;
int defaultOrgLifespan;
int retirementTimeSpan;
|
GameClock clock;
|
ShprAlex/SproutLife
|
src/com/sproutlife/model/echosystem/Echosystem.java
|
// Path: src/com/sproutlife/model/GameClock.java
// public class GameClock {
// private int time;
//
// public GameClock() {
// time = 0;
// }
//
// public int getTime() {
// return time;
// }
//
// void increment() {
// time++;
// }
//
// void reset() {
// this.time = 0;
// }
// }
//
// Path: src/com/sproutlife/model/seed/Seed.java
// public class Seed {
//
// protected SeedSproutPattern pattern;
// public Point position = null;
// public Rotation rotation;
// public int seedBorder = 1;
// public Point parentPosition;
// //Organism organism;
//
// public Seed(SeedSproutPattern pattern, Rotation r) {
// this.pattern = pattern;
// this.rotation = r;
// }
//
// public Seed(SeedSproutPattern pattern) {
// this(pattern, Rotations.get());
// }
//
// public Rotation getRotation() {
// return rotation;
// }
//
// public Point getPosition() {
// return position;
// }
//
// public void setPosition(int x, int y) {
// this.position = new Point(x,y);
// }
//
// public int getSeedBorder() {
// return seedBorder;
// }
//
// public void setSeedBorder(int b) {
// this.seedBorder = b;
// }
//
// public Point getParentPosition() {
// return parentPosition;
// }
//
// public void setParentPosition(Point parentPosition) {
// this.parentPosition = parentPosition;
// }
// /*
// public Organism getOrganism() {
// return organism;
// }
//
// public void setOrganism(Organism organism) {
// this.organism = organism;
// }
// */
//
// public SeedSproutPattern getSeedSproutPattern() {
// return pattern;
// }
//
// public BitPattern getSeedPattern() {
// return pattern.getSeedPattern();
// }
//
// public BitPattern getSproutPattern() {
// return pattern.getSproutPattern();
// }
//
// public boolean getSeedBit(int x, int y) {
// return getSeedPattern().getBit(x, y, getRotation());
// }
//
// public boolean getSproutBit(int x, int y) {
// return getSproutPattern().getBit(x, y, getRotation());
// }
//
// public int getSeedWidth() {
// return getSeedPattern().getWidth(getRotation());
// }
//
// public int getSeedHeight() {
// return getSeedPattern().getHeight(getRotation());
// }
//
// public int getSproutWidth() {
// return getSproutPattern().getWidth(getRotation());
// }
//
// public int getSproutHeight() {
// return getSproutPattern().getHeight(getRotation());
// }
//
// public Point getSproutOffset() {
// return Rotations.offsetToBoard(
// pattern.getSproutOffset(),
// getSeedPattern(),
// getSproutPattern(),
// getRotation());
// }
//
// public Point getSproutPosition() {
// Point sproutOffset = getSproutOffset();
// return new Point(position.x + sproutOffset.x, position.y + sproutOffset.y);
// }
//
// public Point getSproutCenter() {
// Point sproutPosition = getSproutPosition();
// Point sproutCenter = getSproutPattern().getCenter(getRotation());
//
// int ssX = sproutPosition.x+sproutCenter.x;
// int ssY = sproutPosition.y+sproutCenter.y;
//
// return new Point(ssX, ssY);
// }
//
// public Point getSeedOnBit() {
// return pattern.getSeedPattern().getOnBit(getRotation());
// }
//
// public Point getSeedOnPosition() {
// Point pos = this.getPosition();
// Point onOffset = this.getSeedOnBit();
// return new Point(pos.x+onOffset.x,pos.y+onOffset.y);
// }
// }
|
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import com.sproutlife.model.GameClock;
import com.sproutlife.model.seed.Seed;
|
/*
* Create a cell but don't add it
*/
public Cell createCell(int x, int y, Organism o) {
return o.createCell(x, y);
}
public void removeCell(int x, int y) {
Cell c = getBoard().getCell(x, y);
if (c != null) {
removeCell(c);
}
}
public void setDefaultOrgLifespan(int orgLifespan) {
this.defaultOrgLifespan = orgLifespan;
}
public int getDefaultOrgLifespan() {
return defaultOrgLifespan;
}
public int getRetirementTimeSpan() {
return retirementTimeSpan;
}
public void setRetirementTimeSpan(int retirementTimeSpan) {
this.retirementTimeSpan = retirementTimeSpan;
}
|
// Path: src/com/sproutlife/model/GameClock.java
// public class GameClock {
// private int time;
//
// public GameClock() {
// time = 0;
// }
//
// public int getTime() {
// return time;
// }
//
// void increment() {
// time++;
// }
//
// void reset() {
// this.time = 0;
// }
// }
//
// Path: src/com/sproutlife/model/seed/Seed.java
// public class Seed {
//
// protected SeedSproutPattern pattern;
// public Point position = null;
// public Rotation rotation;
// public int seedBorder = 1;
// public Point parentPosition;
// //Organism organism;
//
// public Seed(SeedSproutPattern pattern, Rotation r) {
// this.pattern = pattern;
// this.rotation = r;
// }
//
// public Seed(SeedSproutPattern pattern) {
// this(pattern, Rotations.get());
// }
//
// public Rotation getRotation() {
// return rotation;
// }
//
// public Point getPosition() {
// return position;
// }
//
// public void setPosition(int x, int y) {
// this.position = new Point(x,y);
// }
//
// public int getSeedBorder() {
// return seedBorder;
// }
//
// public void setSeedBorder(int b) {
// this.seedBorder = b;
// }
//
// public Point getParentPosition() {
// return parentPosition;
// }
//
// public void setParentPosition(Point parentPosition) {
// this.parentPosition = parentPosition;
// }
// /*
// public Organism getOrganism() {
// return organism;
// }
//
// public void setOrganism(Organism organism) {
// this.organism = organism;
// }
// */
//
// public SeedSproutPattern getSeedSproutPattern() {
// return pattern;
// }
//
// public BitPattern getSeedPattern() {
// return pattern.getSeedPattern();
// }
//
// public BitPattern getSproutPattern() {
// return pattern.getSproutPattern();
// }
//
// public boolean getSeedBit(int x, int y) {
// return getSeedPattern().getBit(x, y, getRotation());
// }
//
// public boolean getSproutBit(int x, int y) {
// return getSproutPattern().getBit(x, y, getRotation());
// }
//
// public int getSeedWidth() {
// return getSeedPattern().getWidth(getRotation());
// }
//
// public int getSeedHeight() {
// return getSeedPattern().getHeight(getRotation());
// }
//
// public int getSproutWidth() {
// return getSproutPattern().getWidth(getRotation());
// }
//
// public int getSproutHeight() {
// return getSproutPattern().getHeight(getRotation());
// }
//
// public Point getSproutOffset() {
// return Rotations.offsetToBoard(
// pattern.getSproutOffset(),
// getSeedPattern(),
// getSproutPattern(),
// getRotation());
// }
//
// public Point getSproutPosition() {
// Point sproutOffset = getSproutOffset();
// return new Point(position.x + sproutOffset.x, position.y + sproutOffset.y);
// }
//
// public Point getSproutCenter() {
// Point sproutPosition = getSproutPosition();
// Point sproutCenter = getSproutPattern().getCenter(getRotation());
//
// int ssX = sproutPosition.x+sproutCenter.x;
// int ssY = sproutPosition.y+sproutCenter.y;
//
// return new Point(ssX, ssY);
// }
//
// public Point getSeedOnBit() {
// return pattern.getSeedPattern().getOnBit(getRotation());
// }
//
// public Point getSeedOnPosition() {
// Point pos = this.getPosition();
// Point onOffset = this.getSeedOnBit();
// return new Point(pos.x+onOffset.x,pos.y+onOffset.y);
// }
// }
// Path: src/com/sproutlife/model/echosystem/Echosystem.java
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import com.sproutlife.model.GameClock;
import com.sproutlife.model.seed.Seed;
/*
* Create a cell but don't add it
*/
public Cell createCell(int x, int y, Organism o) {
return o.createCell(x, y);
}
public void removeCell(int x, int y) {
Cell c = getBoard().getCell(x, y);
if (c != null) {
removeCell(c);
}
}
public void setDefaultOrgLifespan(int orgLifespan) {
this.defaultOrgLifespan = orgLifespan;
}
public int getDefaultOrgLifespan() {
return defaultOrgLifespan;
}
public int getRetirementTimeSpan() {
return retirementTimeSpan;
}
public void setRetirementTimeSpan(int retirementTimeSpan) {
this.retirementTimeSpan = retirementTimeSpan;
}
|
public Organism createOrganism(int x, int y, Organism parent, Seed seed) {
|
JetBrains/teamcity-dottrace
|
dotTrace-agent/src/main/java/jetbrains/buildServer/dotTrace/agent/BuildPublisher.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/StatisticMessage.java
// public class StatisticMessage extends MessageWithAttributes {
// public static final String MESSAGE_NAME = "dotTraceStatistic";
// private static final String METHOD_STATISTIC_MESSAGE_ATTR = "methodName";
// private static final String THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "totalTimeThreshold";
// private static final String THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR = "ownTimeThreshold";
// private static final String MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "measuredTotalTime";
// private static final String MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR = "measuredOwnTime";
//
// public StatisticMessage(
// @NotNull final String methodName,
// @NotNull final String totalTimeThreshold,
// @NotNull final String ownTimeThreshold,
// @NotNull final String measuredTotalTime,
// @NotNull final String measuredOwnTime) {
// super(
// MESSAGE_NAME,
// CollectionsUtil.asMap(
// METHOD_STATISTIC_MESSAGE_ATTR, methodName,
// THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, totalTimeThreshold,
// THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR, ownTimeThreshold,
// MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, measuredTotalTime,
// MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR, measuredOwnTime));
// }
//
// private StatisticMessage(@NotNull final Map<String, String> attributes) {
// super(MESSAGE_NAME, attributes);
// }
//
// @Nullable
// public static StatisticMessage tryParse(@NotNull final ServiceMessage message) {
// if(!MESSAGE_NAME.equalsIgnoreCase(message.getMessageName())) {
// return null;
// }
//
// return new StatisticMessage(message.getAttributes());
// }
//
// @NotNull
// public String getMethodName() {
// return getAttributes().get(METHOD_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getOwnTimeThreshold() {
// return getAttributes().get(THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getTotalTimeThreshold() {
// return getAttributes().get(THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredOwnTime() {
// return getAttributes().get(MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredTotalTime() {
// return getAttributes().get(MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// final StatisticMessage statisticMessage = (StatisticMessage)o;
//
// if (!getMethodName().equals(statisticMessage.getMethodName())) return false;
// if (!getTotalTimeThreshold().equals(statisticMessage.getTotalTimeThreshold())) return false;
// if (!getOwnTimeThreshold().equals(statisticMessage.getOwnTimeThreshold())) return false;
// if (!getMeasuredTotalTime().equals(statisticMessage.getMeasuredTotalTime())) return false;
// return getMeasuredOwnTime().equals(statisticMessage.getMeasuredOwnTime());
//
// }
//
// @Override
// public int hashCode() {
// int result = getMethodName().hashCode();
// result = 31 * result + getTotalTimeThreshold().hashCode();
// result = 31 * result + getOwnTimeThreshold().hashCode();
// result = 31 * result + getMeasuredTotalTime().hashCode();
// result = 31 * result + getMeasuredOwnTime().hashCode();
// return result;
// }
// }
|
import com.intellij.openapi.util.text.StringUtil;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.StatisticMessage;
import org.jetbrains.annotations.NotNull;
|
myThresholdsParser = thresholdsParser;
myAfterBuildPublisher = afterBuildPublisher;
myParametersService = parametersService;
myFileService = fileService;
myLoggerService = loggerService;
}
@Override
public void publishBeforeBuildFile(@NotNull final CommandLineExecutionContext commandLineExecutionContext, @NotNull final File file, @NotNull final String content) {
}
@Override
public void publishAfterBuildArtifactFile(@NotNull final CommandLineExecutionContext commandLineExecutionContext, @NotNull final File reportFile) {
myAfterBuildPublisher.publishAfterBuildArtifactFile(commandLineExecutionContext, reportFile);
Metrics thresholdValues;
String thresholdsStr = myParametersService.tryGetRunnerParameter(Constants.THRESHOLDS_VAR);
if(!StringUtil.isEmptyOrSpaces(thresholdsStr)) {
thresholdValues = myThresholdsParser.parse(thresholdsStr);
}
else {
return;
}
try {
final String reportContent = myFileService.readAllTextFile(reportFile);
final Metrics measuredValues = myReportParser.parse(reportContent);
for (Metric measuredValue : measuredValues.getMetrics()) {
for (final Metric thresholdValue : thresholdValues.getMetrics()) {
if(measuredValue.getMethodName().startsWith(thresholdValue.getMethodName())) {
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/StatisticMessage.java
// public class StatisticMessage extends MessageWithAttributes {
// public static final String MESSAGE_NAME = "dotTraceStatistic";
// private static final String METHOD_STATISTIC_MESSAGE_ATTR = "methodName";
// private static final String THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "totalTimeThreshold";
// private static final String THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR = "ownTimeThreshold";
// private static final String MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "measuredTotalTime";
// private static final String MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR = "measuredOwnTime";
//
// public StatisticMessage(
// @NotNull final String methodName,
// @NotNull final String totalTimeThreshold,
// @NotNull final String ownTimeThreshold,
// @NotNull final String measuredTotalTime,
// @NotNull final String measuredOwnTime) {
// super(
// MESSAGE_NAME,
// CollectionsUtil.asMap(
// METHOD_STATISTIC_MESSAGE_ATTR, methodName,
// THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, totalTimeThreshold,
// THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR, ownTimeThreshold,
// MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, measuredTotalTime,
// MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR, measuredOwnTime));
// }
//
// private StatisticMessage(@NotNull final Map<String, String> attributes) {
// super(MESSAGE_NAME, attributes);
// }
//
// @Nullable
// public static StatisticMessage tryParse(@NotNull final ServiceMessage message) {
// if(!MESSAGE_NAME.equalsIgnoreCase(message.getMessageName())) {
// return null;
// }
//
// return new StatisticMessage(message.getAttributes());
// }
//
// @NotNull
// public String getMethodName() {
// return getAttributes().get(METHOD_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getOwnTimeThreshold() {
// return getAttributes().get(THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getTotalTimeThreshold() {
// return getAttributes().get(THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredOwnTime() {
// return getAttributes().get(MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredTotalTime() {
// return getAttributes().get(MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// final StatisticMessage statisticMessage = (StatisticMessage)o;
//
// if (!getMethodName().equals(statisticMessage.getMethodName())) return false;
// if (!getTotalTimeThreshold().equals(statisticMessage.getTotalTimeThreshold())) return false;
// if (!getOwnTimeThreshold().equals(statisticMessage.getOwnTimeThreshold())) return false;
// if (!getMeasuredTotalTime().equals(statisticMessage.getMeasuredTotalTime())) return false;
// return getMeasuredOwnTime().equals(statisticMessage.getMeasuredOwnTime());
//
// }
//
// @Override
// public int hashCode() {
// int result = getMethodName().hashCode();
// result = 31 * result + getTotalTimeThreshold().hashCode();
// result = 31 * result + getOwnTimeThreshold().hashCode();
// result = 31 * result + getMeasuredTotalTime().hashCode();
// result = 31 * result + getMeasuredOwnTime().hashCode();
// return result;
// }
// }
// Path: dotTrace-agent/src/main/java/jetbrains/buildServer/dotTrace/agent/BuildPublisher.java
import com.intellij.openapi.util.text.StringUtil;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.StatisticMessage;
import org.jetbrains.annotations.NotNull;
myThresholdsParser = thresholdsParser;
myAfterBuildPublisher = afterBuildPublisher;
myParametersService = parametersService;
myFileService = fileService;
myLoggerService = loggerService;
}
@Override
public void publishBeforeBuildFile(@NotNull final CommandLineExecutionContext commandLineExecutionContext, @NotNull final File file, @NotNull final String content) {
}
@Override
public void publishAfterBuildArtifactFile(@NotNull final CommandLineExecutionContext commandLineExecutionContext, @NotNull final File reportFile) {
myAfterBuildPublisher.publishAfterBuildArtifactFile(commandLineExecutionContext, reportFile);
Metrics thresholdValues;
String thresholdsStr = myParametersService.tryGetRunnerParameter(Constants.THRESHOLDS_VAR);
if(!StringUtil.isEmptyOrSpaces(thresholdsStr)) {
thresholdValues = myThresholdsParser.parse(thresholdsStr);
}
else {
return;
}
try {
final String reportContent = myFileService.readAllTextFile(reportFile);
final Metrics measuredValues = myReportParser.parse(reportContent);
for (Metric measuredValue : measuredValues.getMetrics()) {
for (final Metric thresholdValue : thresholdValues.getMetrics()) {
if(measuredValue.getMethodName().startsWith(thresholdValue.getMethodName())) {
|
myLoggerService.onMessage(new StatisticMessage(measuredValue.getMethodName(), thresholdValue.getTotalTime(), thresholdValue.getOwnTime(), measuredValue.getTotalTime(), measuredValue.getOwnTime()));
|
JetBrains/teamcity-dottrace
|
dotTrace-agent/src/main/java/jetbrains/buildServer/dotTrace/agent/DotTraceSetupBuilder.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
|
import com.intellij.openapi.util.text.StringUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
|
private final RunnerAssertions myAssertions;
public DotTraceSetupBuilder(
@NotNull final ResourceGenerator<Context> projectGenerator,
@NotNull final ResourceGenerator<Context> patternGenerator,
@NotNull final ResourceGenerator<Context> cmdGenerator,
@NotNull final ResourcePublisher beforeBuildPublisher,
@NotNull final ResourcePublisher dotTraceBuildPublisher,
@NotNull final ResourcePublisher dotTraceSnapshotsPublisher,
@NotNull final RunnerParametersService parametersService,
@NotNull final FileService fileService,
@NotNull final RunnerAssertions assertions) {
myProjectGenerator = projectGenerator;
myPatternGenerator = patternGenerator;
myCmdGenerator = cmdGenerator;
myBeforeBuildPublisher = beforeBuildPublisher;
myDotTraceBuildPublisher = dotTraceBuildPublisher;
myDotTraceSnapshotsPublisher = dotTraceSnapshotsPublisher;
myParametersService = parametersService;
myFileService = fileService;
myAssertions = assertions;
}
@Override
@NotNull
public Iterable<CommandLineSetup> build(@NotNull final CommandLineSetup baseSetup) {
if(myAssertions.contains(RunnerAssertions.Assertion.PROFILING_IS_NOT_ALLOWED)) {
return Collections.singleton(baseSetup);
}
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
// Path: dotTrace-agent/src/main/java/jetbrains/buildServer/dotTrace/agent/DotTraceSetupBuilder.java
import com.intellij.openapi.util.text.StringUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
private final RunnerAssertions myAssertions;
public DotTraceSetupBuilder(
@NotNull final ResourceGenerator<Context> projectGenerator,
@NotNull final ResourceGenerator<Context> patternGenerator,
@NotNull final ResourceGenerator<Context> cmdGenerator,
@NotNull final ResourcePublisher beforeBuildPublisher,
@NotNull final ResourcePublisher dotTraceBuildPublisher,
@NotNull final ResourcePublisher dotTraceSnapshotsPublisher,
@NotNull final RunnerParametersService parametersService,
@NotNull final FileService fileService,
@NotNull final RunnerAssertions assertions) {
myProjectGenerator = projectGenerator;
myPatternGenerator = patternGenerator;
myCmdGenerator = cmdGenerator;
myBeforeBuildPublisher = beforeBuildPublisher;
myDotTraceBuildPublisher = dotTraceBuildPublisher;
myDotTraceSnapshotsPublisher = dotTraceSnapshotsPublisher;
myParametersService = parametersService;
myFileService = fileService;
myAssertions = assertions;
}
@Override
@NotNull
public Iterable<CommandLineSetup> build(@NotNull final CommandLineSetup baseSetup) {
if(myAssertions.contains(RunnerAssertions.Assertion.PROFILING_IS_NOT_ALLOWED)) {
return Collections.singleton(baseSetup);
}
|
final String dotTraceTool = myParametersService.tryGetRunnerParameter(Constants.USE_VAR);
|
JetBrains/teamcity-dottrace
|
dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/CmdGeneratorTest.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
|
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
|
new File("root"),
new File("path", "abc"),
"ProfilerCmd" + ourlineSeparator
+ "@SET EXIT_CODE=%ERRORLEVEL%" + ourlineSeparator
+ "ReporterCmd" + ourlineSeparator
+ "@EXIT %EXIT_CODE%"
},
};
}
@Test(dataProvider = "parseGenerateContentCases")
public void shouldGenerateContent(@Nullable final File checkoutPath, @NotNull final File toolPath, @NotNull final String expectedContent) {
// Given
final File projectFile = new File("project");
final File snapshotFile = new File(new File("snapshots"), "snapshot.dtp");
final File patternsFile = new File("patterns");
final File reportFile = new File("report");
File path;
if(checkoutPath != null) {
path = new File(checkoutPath, toolPath.getPath());
}
else {
path = toolPath;
}
final File consoleProfilerFile = new File(path, CmdGenerator.DOT_TRACE_EXE_NAME);
final File reporterFile = new File(path, CmdGenerator.DOT_TRACE_REPORTER_EXE_NAME);
final CommandLineSetup setup = new CommandLineSetup("tool", Collections.<CommandLineArgument>emptyList(), Collections.<CommandLineResource>emptyList());
myCtx.checking(new Expectations() {{
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
// Path: dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/CmdGeneratorTest.java
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
new File("root"),
new File("path", "abc"),
"ProfilerCmd" + ourlineSeparator
+ "@SET EXIT_CODE=%ERRORLEVEL%" + ourlineSeparator
+ "ReporterCmd" + ourlineSeparator
+ "@EXIT %EXIT_CODE%"
},
};
}
@Test(dataProvider = "parseGenerateContentCases")
public void shouldGenerateContent(@Nullable final File checkoutPath, @NotNull final File toolPath, @NotNull final String expectedContent) {
// Given
final File projectFile = new File("project");
final File snapshotFile = new File(new File("snapshots"), "snapshot.dtp");
final File patternsFile = new File("patterns");
final File reportFile = new File("report");
File path;
if(checkoutPath != null) {
path = new File(checkoutPath, toolPath.getPath());
}
else {
path = toolPath;
}
final File consoleProfilerFile = new File(path, CmdGenerator.DOT_TRACE_EXE_NAME);
final File reporterFile = new File(path, CmdGenerator.DOT_TRACE_REPORTER_EXE_NAME);
final CommandLineSetup setup = new CommandLineSetup("tool", Collections.<CommandLineArgument>emptyList(), Collections.<CommandLineResource>emptyList());
myCtx.checking(new Expectations() {{
|
oneOf(myRunnerParametersService).getRunnerParameter(Constants.PATH_VAR);
|
JetBrains/teamcity-dottrace
|
dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/ProjectGeneratorTest.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/MeasureType.java
// public enum MeasureType {
// SAMPLING("sampling", "Sampling", "Sampling"),
// TRACING("tracing", "Tracing", ""),
// LINE_BY_LINE("line-by-line", "Line-by-line", "TracingInject");
//
// private final String myValue;
// private final String myDescription;
// private final String myId;
//
// MeasureType(@NotNull final String value, @NotNull final String description, @NotNull final String id) {
// myValue = value;
// myDescription = description;
// myId = id;
// }
//
// @NotNull
// public String getValue() {
// return myValue;
// }
//
// @NotNull
// public String getDescription() {
// return myDescription;
// }
//
// @NotNull
// @Override
// public String toString() {
// return myDescription;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
// }
|
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.MeasureType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import static org.assertj.core.api.BDDAssertions.then;
|
public void setUp()
{
myCtx = new Mockery();
//noinspection unchecked
myProcessFiltersParser = (TextParser<List<ProcessFilter>>)myCtx.mock(TextParser.class);
myFileService = myCtx.mock(FileService.class);
myXmlDocumentManager = myCtx.mock(XmlDocumentManager.class);
myCommandLineArgumentsService = myCtx.mock(CommandLineArgumentsService.class);
myRunnerParametersService = myCtx.mock(RunnerParametersService.class);
}
@DataProvider(name = "generateContentCases")
public Object[][] getGenerateContentCases() {
return new Object[][] {
{ "True", "True", null, Collections.emptyList(), "", null},
{ "False", "False", null, Collections.emptyList(), "", null},
{ "", "True", null, Collections.emptyList(), "" , null},
{ null, "True", null, Collections.emptyList(), "", null},
{ "True", "True", "nunit-console*", Arrays.asList(new ProcessFilter("nunit-console*")), "<Item/><Item><ProcessNameFilter>nunit-console*</ProcessNameFilter><Type>Deny</Type></Item>", null},
{ "True", "True", "nunit-console*" + ourlineSeparator + "Abc", Arrays.asList(new ProcessFilter("nunit-console*"), new ProcessFilter("Abc")), "<Item/><Item><ProcessNameFilter>nunit-console*</ProcessNameFilter><Type>Deny</Type></Item><Item><ProcessNameFilter>Abc</ProcessNameFilter><Type>Deny</Type></Item>", null},
};
}
@Test(dataProvider = "generateContentCases")
public void shouldGenerateContent(
@Nullable final String profileChildProcesses,
@NotNull final String profileChildProcessesXmlValue,
@Nullable final String processFilters,
@NotNull final List<ProcessFilter> processFiltersList,
@NotNull final String processFiltersXmlValue,
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/MeasureType.java
// public enum MeasureType {
// SAMPLING("sampling", "Sampling", "Sampling"),
// TRACING("tracing", "Tracing", ""),
// LINE_BY_LINE("line-by-line", "Line-by-line", "TracingInject");
//
// private final String myValue;
// private final String myDescription;
// private final String myId;
//
// MeasureType(@NotNull final String value, @NotNull final String description, @NotNull final String id) {
// myValue = value;
// myDescription = description;
// myId = id;
// }
//
// @NotNull
// public String getValue() {
// return myValue;
// }
//
// @NotNull
// public String getDescription() {
// return myDescription;
// }
//
// @NotNull
// @Override
// public String toString() {
// return myDescription;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
// }
// Path: dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/ProjectGeneratorTest.java
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.MeasureType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import static org.assertj.core.api.BDDAssertions.then;
public void setUp()
{
myCtx = new Mockery();
//noinspection unchecked
myProcessFiltersParser = (TextParser<List<ProcessFilter>>)myCtx.mock(TextParser.class);
myFileService = myCtx.mock(FileService.class);
myXmlDocumentManager = myCtx.mock(XmlDocumentManager.class);
myCommandLineArgumentsService = myCtx.mock(CommandLineArgumentsService.class);
myRunnerParametersService = myCtx.mock(RunnerParametersService.class);
}
@DataProvider(name = "generateContentCases")
public Object[][] getGenerateContentCases() {
return new Object[][] {
{ "True", "True", null, Collections.emptyList(), "", null},
{ "False", "False", null, Collections.emptyList(), "", null},
{ "", "True", null, Collections.emptyList(), "" , null},
{ null, "True", null, Collections.emptyList(), "", null},
{ "True", "True", "nunit-console*", Arrays.asList(new ProcessFilter("nunit-console*")), "<Item/><Item><ProcessNameFilter>nunit-console*</ProcessNameFilter><Type>Deny</Type></Item>", null},
{ "True", "True", "nunit-console*" + ourlineSeparator + "Abc", Arrays.asList(new ProcessFilter("nunit-console*"), new ProcessFilter("Abc")), "<Item/><Item><ProcessNameFilter>nunit-console*</ProcessNameFilter><Type>Deny</Type></Item><Item><ProcessNameFilter>Abc</ProcessNameFilter><Type>Deny</Type></Item>", null},
};
}
@Test(dataProvider = "generateContentCases")
public void shouldGenerateContent(
@Nullable final String profileChildProcesses,
@NotNull final String profileChildProcessesXmlValue,
@Nullable final String processFilters,
@NotNull final List<ProcessFilter> processFiltersList,
@NotNull final String processFiltersXmlValue,
|
@Nullable MeasureType measureType) {
|
JetBrains/teamcity-dottrace
|
dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/ProjectGeneratorTest.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/MeasureType.java
// public enum MeasureType {
// SAMPLING("sampling", "Sampling", "Sampling"),
// TRACING("tracing", "Tracing", ""),
// LINE_BY_LINE("line-by-line", "Line-by-line", "TracingInject");
//
// private final String myValue;
// private final String myDescription;
// private final String myId;
//
// MeasureType(@NotNull final String value, @NotNull final String description, @NotNull final String id) {
// myValue = value;
// myDescription = description;
// myId = id;
// }
//
// @NotNull
// public String getValue() {
// return myValue;
// }
//
// @NotNull
// public String getDescription() {
// return myDescription;
// }
//
// @NotNull
// @Override
// public String toString() {
// return myDescription;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
// }
|
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.MeasureType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import static org.assertj.core.api.BDDAssertions.then;
|
"</Info>" +
"</root>";
final CommandLineSetup setup = new CommandLineSetup(
"wd" + File.separator + "tool",
Arrays.asList(
new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER),
new CommandLineArgument("arg2", CommandLineArgument.Type.PARAMETER)),
Collections.<CommandLineResource>emptyList());
myCtx.checking(new Expectations() {{
oneOf(myXmlDocumentManager).createDocument();
will(returnValue(ourDocManager.createDocument()));
//noinspection unchecked
oneOf(myXmlDocumentManager).convertDocumentToString(with(any(Document.class)), with(any(Map.class)));
will(new CustomAction("doc") {
@Override
public Object invoke(Invocation invocation) throws Throwable {
//noinspection unchecked
return ourDocManager.convertDocumentToString((Document)invocation.getParameter(0), (Map<String, String>)invocation.getParameter(1));
}
});
oneOf(myCommandLineArgumentsService).createCommandLineString(setup.getArgs());
will(returnValue("arg1 arg2"));
oneOf(myFileService).getCheckoutDirectory();
will(returnValue(new File("wd")));
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/MeasureType.java
// public enum MeasureType {
// SAMPLING("sampling", "Sampling", "Sampling"),
// TRACING("tracing", "Tracing", ""),
// LINE_BY_LINE("line-by-line", "Line-by-line", "TracingInject");
//
// private final String myValue;
// private final String myDescription;
// private final String myId;
//
// MeasureType(@NotNull final String value, @NotNull final String description, @NotNull final String id) {
// myValue = value;
// myDescription = description;
// myId = id;
// }
//
// @NotNull
// public String getValue() {
// return myValue;
// }
//
// @NotNull
// public String getDescription() {
// return myDescription;
// }
//
// @NotNull
// @Override
// public String toString() {
// return myDescription;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
// }
// Path: dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/ProjectGeneratorTest.java
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.MeasureType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import static org.assertj.core.api.BDDAssertions.then;
"</Info>" +
"</root>";
final CommandLineSetup setup = new CommandLineSetup(
"wd" + File.separator + "tool",
Arrays.asList(
new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER),
new CommandLineArgument("arg2", CommandLineArgument.Type.PARAMETER)),
Collections.<CommandLineResource>emptyList());
myCtx.checking(new Expectations() {{
oneOf(myXmlDocumentManager).createDocument();
will(returnValue(ourDocManager.createDocument()));
//noinspection unchecked
oneOf(myXmlDocumentManager).convertDocumentToString(with(any(Document.class)), with(any(Map.class)));
will(new CustomAction("doc") {
@Override
public Object invoke(Invocation invocation) throws Throwable {
//noinspection unchecked
return ourDocManager.convertDocumentToString((Document)invocation.getParameter(0), (Map<String, String>)invocation.getParameter(1));
}
});
oneOf(myCommandLineArgumentsService).createCommandLineString(setup.getArgs());
will(returnValue("arg1 arg2"));
oneOf(myFileService).getCheckoutDirectory();
will(returnValue(new File("wd")));
|
oneOf(myRunnerParametersService).tryGetRunnerParameter(Constants.PROFILE_CHILD_PROCESSES_VAR);
|
JetBrains/teamcity-dottrace
|
dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/PatternsGeneratorTest.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
|
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
|
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.dotTrace.agent;
public class PatternsGeneratorTest {
private Mockery myCtx;
private TextParser<Metrics> myReportPatternsParser;
private RunnerParametersService myRunnerParametersService;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
//noinspection unchecked
myReportPatternsParser = (TextParser<Metrics>)myCtx.mock(TextParser.class);
myRunnerParametersService = myCtx.mock(RunnerParametersService.class);
}
@Test
public void shouldGenerateContent() {
// Given
String expectedContent = "<Patterns>" +
"<Pattern>Method1</Pattern>" +
"<Pattern>Method2</Pattern>" +
"</Patterns>";
final CommandLineSetup setup = new CommandLineSetup("tool", Collections.<CommandLineArgument>emptyList(), Collections.<CommandLineResource>emptyList());
myCtx.checking(new Expectations() {{
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
// Path: dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/PatternsGeneratorTest.java
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.dotTrace.agent;
public class PatternsGeneratorTest {
private Mockery myCtx;
private TextParser<Metrics> myReportPatternsParser;
private RunnerParametersService myRunnerParametersService;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
//noinspection unchecked
myReportPatternsParser = (TextParser<Metrics>)myCtx.mock(TextParser.class);
myRunnerParametersService = myCtx.mock(RunnerParametersService.class);
}
@Test
public void shouldGenerateContent() {
// Given
String expectedContent = "<Patterns>" +
"<Pattern>Method1</Pattern>" +
"<Pattern>Method2</Pattern>" +
"</Patterns>";
final CommandLineSetup setup = new CommandLineSetup("tool", Collections.<CommandLineArgument>emptyList(), Collections.<CommandLineResource>emptyList());
myCtx.checking(new Expectations() {{
|
oneOf(myRunnerParametersService).tryGetRunnerParameter(Constants.THRESHOLDS_VAR);
|
JetBrains/teamcity-dottrace
|
dotTrace-agent/src/main/java/jetbrains/buildServer/dotTrace/agent/ProjectGenerator.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/MeasureType.java
// public enum MeasureType {
// SAMPLING("sampling", "Sampling", "Sampling"),
// TRACING("tracing", "Tracing", ""),
// LINE_BY_LINE("line-by-line", "Line-by-line", "TracingInject");
//
// private final String myValue;
// private final String myDescription;
// private final String myId;
//
// MeasureType(@NotNull final String value, @NotNull final String description, @NotNull final String id) {
// myValue = value;
// myDescription = description;
// myId = id;
// }
//
// @NotNull
// public String getValue() {
// return myValue;
// }
//
// @NotNull
// public String getDescription() {
// return myDescription;
// }
//
// @NotNull
// @Override
// public String toString() {
// return myDescription;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
// }
|
import com.intellij.openapi.util.text.StringUtil;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.MeasureType;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
|
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.dotTrace.agent;
public class ProjectGenerator implements ResourceGenerator<Context> {
private static final Map<String, String> outDocumentProperties = new HashMap<String, String>();
private static final String ROOT_ELEMENT = "root";
private static final String TYPE_ATTR = "type";
private static final String TYPE_ELEMENT = "Type";
private static final String HOST_PARAMETERS_ELEMENT = "HostParameters";
private static final String TYPE_LOCAL_HOST_PARAMETERS = "LocalHostParameters";
private static final String ARGUMENT_ELEMENT = "Argument";
private static final String ARGUMENTS_ELEMENT = "Arguments";
private static final String FILE_NAME_ELEMENT = "FileName";
private static final String PROFILE_CHILD_PROCESSES_ELEMENT = "ProfileChildProcesses";
private static final String WORKING_DIRECTORY_ELEMENT = "WorkingDirectory";
private static final String INFO_ELEMENT = "Info";
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/MeasureType.java
// public enum MeasureType {
// SAMPLING("sampling", "Sampling", "Sampling"),
// TRACING("tracing", "Tracing", ""),
// LINE_BY_LINE("line-by-line", "Line-by-line", "TracingInject");
//
// private final String myValue;
// private final String myDescription;
// private final String myId;
//
// MeasureType(@NotNull final String value, @NotNull final String description, @NotNull final String id) {
// myValue = value;
// myDescription = description;
// myId = id;
// }
//
// @NotNull
// public String getValue() {
// return myValue;
// }
//
// @NotNull
// public String getDescription() {
// return myDescription;
// }
//
// @NotNull
// @Override
// public String toString() {
// return myDescription;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
// }
// Path: dotTrace-agent/src/main/java/jetbrains/buildServer/dotTrace/agent/ProjectGenerator.java
import com.intellij.openapi.util.text.StringUtil;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.MeasureType;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.dotTrace.agent;
public class ProjectGenerator implements ResourceGenerator<Context> {
private static final Map<String, String> outDocumentProperties = new HashMap<String, String>();
private static final String ROOT_ELEMENT = "root";
private static final String TYPE_ATTR = "type";
private static final String TYPE_ELEMENT = "Type";
private static final String HOST_PARAMETERS_ELEMENT = "HostParameters";
private static final String TYPE_LOCAL_HOST_PARAMETERS = "LocalHostParameters";
private static final String ARGUMENT_ELEMENT = "Argument";
private static final String ARGUMENTS_ELEMENT = "Arguments";
private static final String FILE_NAME_ELEMENT = "FileName";
private static final String PROFILE_CHILD_PROCESSES_ELEMENT = "ProfileChildProcesses";
private static final String WORKING_DIRECTORY_ELEMENT = "WorkingDirectory";
private static final String INFO_ELEMENT = "Info";
|
private static final String MEASURE_TYPE_ELEMENT = "MeasureType";
|
JetBrains/teamcity-dottrace
|
dotTrace-agent/src/main/java/jetbrains/buildServer/dotTrace/agent/ProjectGenerator.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/MeasureType.java
// public enum MeasureType {
// SAMPLING("sampling", "Sampling", "Sampling"),
// TRACING("tracing", "Tracing", ""),
// LINE_BY_LINE("line-by-line", "Line-by-line", "TracingInject");
//
// private final String myValue;
// private final String myDescription;
// private final String myId;
//
// MeasureType(@NotNull final String value, @NotNull final String description, @NotNull final String id) {
// myValue = value;
// myDescription = description;
// myId = id;
// }
//
// @NotNull
// public String getValue() {
// return myValue;
// }
//
// @NotNull
// public String getDescription() {
// return myDescription;
// }
//
// @NotNull
// @Override
// public String toString() {
// return myDescription;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
// }
|
import com.intellij.openapi.util.text.StringUtil;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.MeasureType;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
|
private final RunnerParametersService myParametersService;
public ProjectGenerator(
@NotNull final TextParser<List<ProcessFilter>> processFiltersParser,
@NotNull final XmlDocumentManager documentManager,
@NotNull final CommandLineArgumentsService commandLineArgumentsService,
@NotNull final FileService fileService,
@NotNull final RunnerParametersService parametersService) {
myProcessFiltersParser = processFiltersParser;
myDocumentManager = documentManager;
myCommandLineArgumentsService = commandLineArgumentsService;
myFileService = fileService;
myParametersService = parametersService;
}
@Override
@NotNull
public String create(@NotNull final Context ctx) {
final Document doc = myDocumentManager.createDocument();
final Element rootElement = doc.createElement(ROOT_ELEMENT);
final Element hostParametersElement = doc.createElement(HOST_PARAMETERS_ELEMENT);
hostParametersElement.setAttribute(TYPE_ATTR, TYPE_LOCAL_HOST_PARAMETERS);
rootElement.appendChild(hostParametersElement);
final Element argumentElement = doc.createElement(ARGUMENT_ELEMENT);
argumentElement.setAttribute(TYPE_ATTR, TYPE_STANDALONE_ARGUMENT);
argumentElement.appendChild(createSimpleElement(doc, ARGUMENTS_ELEMENT, myCommandLineArgumentsService.createCommandLineString(ctx.getBaseSetup().getArgs())));
argumentElement.appendChild(createSimpleElement(doc, FILE_NAME_ELEMENT, ctx.getBaseSetup().getToolPath()));
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
//
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/MeasureType.java
// public enum MeasureType {
// SAMPLING("sampling", "Sampling", "Sampling"),
// TRACING("tracing", "Tracing", ""),
// LINE_BY_LINE("line-by-line", "Line-by-line", "TracingInject");
//
// private final String myValue;
// private final String myDescription;
// private final String myId;
//
// MeasureType(@NotNull final String value, @NotNull final String description, @NotNull final String id) {
// myValue = value;
// myDescription = description;
// myId = id;
// }
//
// @NotNull
// public String getValue() {
// return myValue;
// }
//
// @NotNull
// public String getDescription() {
// return myDescription;
// }
//
// @NotNull
// @Override
// public String toString() {
// return myDescription;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
// }
// Path: dotTrace-agent/src/main/java/jetbrains/buildServer/dotTrace/agent/ProjectGenerator.java
import com.intellij.openapi.util.text.StringUtil;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.dotTrace.MeasureType;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
private final RunnerParametersService myParametersService;
public ProjectGenerator(
@NotNull final TextParser<List<ProcessFilter>> processFiltersParser,
@NotNull final XmlDocumentManager documentManager,
@NotNull final CommandLineArgumentsService commandLineArgumentsService,
@NotNull final FileService fileService,
@NotNull final RunnerParametersService parametersService) {
myProcessFiltersParser = processFiltersParser;
myDocumentManager = documentManager;
myCommandLineArgumentsService = commandLineArgumentsService;
myFileService = fileService;
myParametersService = parametersService;
}
@Override
@NotNull
public String create(@NotNull final Context ctx) {
final Document doc = myDocumentManager.createDocument();
final Element rootElement = doc.createElement(ROOT_ELEMENT);
final Element hostParametersElement = doc.createElement(HOST_PARAMETERS_ELEMENT);
hostParametersElement.setAttribute(TYPE_ATTR, TYPE_LOCAL_HOST_PARAMETERS);
rootElement.appendChild(hostParametersElement);
final Element argumentElement = doc.createElement(ARGUMENT_ELEMENT);
argumentElement.setAttribute(TYPE_ATTR, TYPE_STANDALONE_ARGUMENT);
argumentElement.appendChild(createSimpleElement(doc, ARGUMENTS_ELEMENT, myCommandLineArgumentsService.createCommandLineString(ctx.getBaseSetup().getArgs())));
argumentElement.appendChild(createSimpleElement(doc, FILE_NAME_ELEMENT, ctx.getBaseSetup().getToolPath()));
|
final String profileChildProcessesStr = myParametersService.tryGetRunnerParameter(Constants.PROFILE_CHILD_PROCESSES_VAR);
|
JetBrains/teamcity-dottrace
|
dotTrace-server/src/main/java/jetbrains/buildServer/dotTrace/server/StatisticProviderImpl.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/StatisticMessage.java
// public class StatisticMessage extends MessageWithAttributes {
// public static final String MESSAGE_NAME = "dotTraceStatistic";
// private static final String METHOD_STATISTIC_MESSAGE_ATTR = "methodName";
// private static final String THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "totalTimeThreshold";
// private static final String THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR = "ownTimeThreshold";
// private static final String MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "measuredTotalTime";
// private static final String MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR = "measuredOwnTime";
//
// public StatisticMessage(
// @NotNull final String methodName,
// @NotNull final String totalTimeThreshold,
// @NotNull final String ownTimeThreshold,
// @NotNull final String measuredTotalTime,
// @NotNull final String measuredOwnTime) {
// super(
// MESSAGE_NAME,
// CollectionsUtil.asMap(
// METHOD_STATISTIC_MESSAGE_ATTR, methodName,
// THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, totalTimeThreshold,
// THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR, ownTimeThreshold,
// MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, measuredTotalTime,
// MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR, measuredOwnTime));
// }
//
// private StatisticMessage(@NotNull final Map<String, String> attributes) {
// super(MESSAGE_NAME, attributes);
// }
//
// @Nullable
// public static StatisticMessage tryParse(@NotNull final ServiceMessage message) {
// if(!MESSAGE_NAME.equalsIgnoreCase(message.getMessageName())) {
// return null;
// }
//
// return new StatisticMessage(message.getAttributes());
// }
//
// @NotNull
// public String getMethodName() {
// return getAttributes().get(METHOD_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getOwnTimeThreshold() {
// return getAttributes().get(THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getTotalTimeThreshold() {
// return getAttributes().get(THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredOwnTime() {
// return getAttributes().get(MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredTotalTime() {
// return getAttributes().get(MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// final StatisticMessage statisticMessage = (StatisticMessage)o;
//
// if (!getMethodName().equals(statisticMessage.getMethodName())) return false;
// if (!getTotalTimeThreshold().equals(statisticMessage.getTotalTimeThreshold())) return false;
// if (!getOwnTimeThreshold().equals(statisticMessage.getOwnTimeThreshold())) return false;
// if (!getMeasuredTotalTime().equals(statisticMessage.getMeasuredTotalTime())) return false;
// return getMeasuredOwnTime().equals(statisticMessage.getMeasuredOwnTime());
//
// }
//
// @Override
// public int hashCode() {
// int result = getMethodName().hashCode();
// result = 31 * result + getTotalTimeThreshold().hashCode();
// result = 31 * result + getOwnTimeThreshold().hashCode();
// result = 31 * result + getMeasuredTotalTime().hashCode();
// result = 31 * result + getMeasuredOwnTime().hashCode();
// return result;
// }
// }
|
import java.math.BigDecimal;
import org.jetbrains.annotations.Nullable;
import jetbrains.buildServer.dotTrace.StatisticMessage;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.BeanFactory;
|
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.dotTrace.server;
public class StatisticProviderImpl implements StatisticProvider {
private final BigDecimalParser myBigDecimalParser;
private final StatisticKeyFactory myStatisticKeyFactory;
private final BeanFactory myBeanFactory;
public StatisticProviderImpl(
@NotNull final BigDecimalParser bigDecimalParser,
@NotNull final StatisticKeyFactory statisticKeyFactory,
@NotNull final BeanFactory beanFactory) {
myBigDecimalParser = bigDecimalParser;
myStatisticKeyFactory = statisticKeyFactory;
myBeanFactory = beanFactory;
}
@Nullable
@Override
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/StatisticMessage.java
// public class StatisticMessage extends MessageWithAttributes {
// public static final String MESSAGE_NAME = "dotTraceStatistic";
// private static final String METHOD_STATISTIC_MESSAGE_ATTR = "methodName";
// private static final String THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "totalTimeThreshold";
// private static final String THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR = "ownTimeThreshold";
// private static final String MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "measuredTotalTime";
// private static final String MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR = "measuredOwnTime";
//
// public StatisticMessage(
// @NotNull final String methodName,
// @NotNull final String totalTimeThreshold,
// @NotNull final String ownTimeThreshold,
// @NotNull final String measuredTotalTime,
// @NotNull final String measuredOwnTime) {
// super(
// MESSAGE_NAME,
// CollectionsUtil.asMap(
// METHOD_STATISTIC_MESSAGE_ATTR, methodName,
// THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, totalTimeThreshold,
// THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR, ownTimeThreshold,
// MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, measuredTotalTime,
// MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR, measuredOwnTime));
// }
//
// private StatisticMessage(@NotNull final Map<String, String> attributes) {
// super(MESSAGE_NAME, attributes);
// }
//
// @Nullable
// public static StatisticMessage tryParse(@NotNull final ServiceMessage message) {
// if(!MESSAGE_NAME.equalsIgnoreCase(message.getMessageName())) {
// return null;
// }
//
// return new StatisticMessage(message.getAttributes());
// }
//
// @NotNull
// public String getMethodName() {
// return getAttributes().get(METHOD_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getOwnTimeThreshold() {
// return getAttributes().get(THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getTotalTimeThreshold() {
// return getAttributes().get(THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredOwnTime() {
// return getAttributes().get(MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredTotalTime() {
// return getAttributes().get(MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// final StatisticMessage statisticMessage = (StatisticMessage)o;
//
// if (!getMethodName().equals(statisticMessage.getMethodName())) return false;
// if (!getTotalTimeThreshold().equals(statisticMessage.getTotalTimeThreshold())) return false;
// if (!getOwnTimeThreshold().equals(statisticMessage.getOwnTimeThreshold())) return false;
// if (!getMeasuredTotalTime().equals(statisticMessage.getMeasuredTotalTime())) return false;
// return getMeasuredOwnTime().equals(statisticMessage.getMeasuredOwnTime());
//
// }
//
// @Override
// public int hashCode() {
// int result = getMethodName().hashCode();
// result = 31 * result + getTotalTimeThreshold().hashCode();
// result = 31 * result + getOwnTimeThreshold().hashCode();
// result = 31 * result + getMeasuredTotalTime().hashCode();
// result = 31 * result + getMeasuredOwnTime().hashCode();
// return result;
// }
// }
// Path: dotTrace-server/src/main/java/jetbrains/buildServer/dotTrace/server/StatisticProviderImpl.java
import java.math.BigDecimal;
import org.jetbrains.annotations.Nullable;
import jetbrains.buildServer.dotTrace.StatisticMessage;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.BeanFactory;
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.dotTrace.server;
public class StatisticProviderImpl implements StatisticProvider {
private final BigDecimalParser myBigDecimalParser;
private final StatisticKeyFactory myStatisticKeyFactory;
private final BeanFactory myBeanFactory;
public StatisticProviderImpl(
@NotNull final BigDecimalParser bigDecimalParser,
@NotNull final StatisticKeyFactory statisticKeyFactory,
@NotNull final BeanFactory beanFactory) {
myBigDecimalParser = bigDecimalParser;
myStatisticKeyFactory = statisticKeyFactory;
myBeanFactory = beanFactory;
}
@Nullable
@Override
|
public Statistic tryCreateStatistic(@NotNull final StatisticMessage statisticMessage, @NotNull final Iterable<HistoryElement> historyProviders) {
|
JetBrains/teamcity-dottrace
|
dotTrace-server/src/test/java/jetbrains/buildServer/dotTrace/server/StatisticProviderTest.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/StatisticMessage.java
// public class StatisticMessage extends MessageWithAttributes {
// public static final String MESSAGE_NAME = "dotTraceStatistic";
// private static final String METHOD_STATISTIC_MESSAGE_ATTR = "methodName";
// private static final String THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "totalTimeThreshold";
// private static final String THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR = "ownTimeThreshold";
// private static final String MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "measuredTotalTime";
// private static final String MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR = "measuredOwnTime";
//
// public StatisticMessage(
// @NotNull final String methodName,
// @NotNull final String totalTimeThreshold,
// @NotNull final String ownTimeThreshold,
// @NotNull final String measuredTotalTime,
// @NotNull final String measuredOwnTime) {
// super(
// MESSAGE_NAME,
// CollectionsUtil.asMap(
// METHOD_STATISTIC_MESSAGE_ATTR, methodName,
// THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, totalTimeThreshold,
// THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR, ownTimeThreshold,
// MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, measuredTotalTime,
// MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR, measuredOwnTime));
// }
//
// private StatisticMessage(@NotNull final Map<String, String> attributes) {
// super(MESSAGE_NAME, attributes);
// }
//
// @Nullable
// public static StatisticMessage tryParse(@NotNull final ServiceMessage message) {
// if(!MESSAGE_NAME.equalsIgnoreCase(message.getMessageName())) {
// return null;
// }
//
// return new StatisticMessage(message.getAttributes());
// }
//
// @NotNull
// public String getMethodName() {
// return getAttributes().get(METHOD_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getOwnTimeThreshold() {
// return getAttributes().get(THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getTotalTimeThreshold() {
// return getAttributes().get(THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredOwnTime() {
// return getAttributes().get(MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredTotalTime() {
// return getAttributes().get(MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// final StatisticMessage statisticMessage = (StatisticMessage)o;
//
// if (!getMethodName().equals(statisticMessage.getMethodName())) return false;
// if (!getTotalTimeThreshold().equals(statisticMessage.getTotalTimeThreshold())) return false;
// if (!getOwnTimeThreshold().equals(statisticMessage.getOwnTimeThreshold())) return false;
// if (!getMeasuredTotalTime().equals(statisticMessage.getMeasuredTotalTime())) return false;
// return getMeasuredOwnTime().equals(statisticMessage.getMeasuredOwnTime());
//
// }
//
// @Override
// public int hashCode() {
// int result = getMethodName().hashCode();
// result = 31 * result + getTotalTimeThreshold().hashCode();
// result = 31 * result + getOwnTimeThreshold().hashCode();
// result = 31 * result + getMeasuredTotalTime().hashCode();
// result = 31 * result + getMeasuredOwnTime().hashCode();
// return result;
// }
// }
|
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.dotTrace.StatisticMessage;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.springframework.beans.factory.BeanFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
|
oneOf(myHistoryElement1).tryGetValue("ownTimeKey");
will(returnValue(new BigDecimal(32)));
oneOf(myValueAggregatorFirst).aggregate(new BigDecimal(32));
allowing(myValueAggregatorLast).isCompleted();
will(returnValue(false));
allowing(myValueAggregatorFirst).isCompleted();
will(returnValue(false));
oneOf(myHistoryElement2).tryGetValue("totalTimeKey");
will(returnValue(new BigDecimal(14)));
oneOf(myValueAggregatorLast).aggregate(new BigDecimal(14));
oneOf(myHistoryElement2).tryGetValue("ownTimeKey");
will(returnValue(new BigDecimal(36)));
oneOf(myValueAggregatorFirst).aggregate(new BigDecimal(36));
oneOf(myValueAggregatorLast).tryGetAggregatedValue();
will(returnValue(PREV_TOTAL_TIME));
oneOf(myValueAggregatorFirst).tryGetAggregatedValue();
will(returnValue(PREV_OWN_TIME));
}});
// When
final StatisticProvider instance = createInstance();
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/StatisticMessage.java
// public class StatisticMessage extends MessageWithAttributes {
// public static final String MESSAGE_NAME = "dotTraceStatistic";
// private static final String METHOD_STATISTIC_MESSAGE_ATTR = "methodName";
// private static final String THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "totalTimeThreshold";
// private static final String THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR = "ownTimeThreshold";
// private static final String MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR = "measuredTotalTime";
// private static final String MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR = "measuredOwnTime";
//
// public StatisticMessage(
// @NotNull final String methodName,
// @NotNull final String totalTimeThreshold,
// @NotNull final String ownTimeThreshold,
// @NotNull final String measuredTotalTime,
// @NotNull final String measuredOwnTime) {
// super(
// MESSAGE_NAME,
// CollectionsUtil.asMap(
// METHOD_STATISTIC_MESSAGE_ATTR, methodName,
// THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, totalTimeThreshold,
// THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR, ownTimeThreshold,
// MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR, measuredTotalTime,
// MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR, measuredOwnTime));
// }
//
// private StatisticMessage(@NotNull final Map<String, String> attributes) {
// super(MESSAGE_NAME, attributes);
// }
//
// @Nullable
// public static StatisticMessage tryParse(@NotNull final ServiceMessage message) {
// if(!MESSAGE_NAME.equalsIgnoreCase(message.getMessageName())) {
// return null;
// }
//
// return new StatisticMessage(message.getAttributes());
// }
//
// @NotNull
// public String getMethodName() {
// return getAttributes().get(METHOD_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getOwnTimeThreshold() {
// return getAttributes().get(THRESHOLD_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getTotalTimeThreshold() {
// return getAttributes().get(THRESHOLD_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredOwnTime() {
// return getAttributes().get(MEASURED_OWN_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @NotNull
// public String getMeasuredTotalTime() {
// return getAttributes().get(MEASURED_TOTAL_TIME_STATISTIC_MESSAGE_ATTR);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// final StatisticMessage statisticMessage = (StatisticMessage)o;
//
// if (!getMethodName().equals(statisticMessage.getMethodName())) return false;
// if (!getTotalTimeThreshold().equals(statisticMessage.getTotalTimeThreshold())) return false;
// if (!getOwnTimeThreshold().equals(statisticMessage.getOwnTimeThreshold())) return false;
// if (!getMeasuredTotalTime().equals(statisticMessage.getMeasuredTotalTime())) return false;
// return getMeasuredOwnTime().equals(statisticMessage.getMeasuredOwnTime());
//
// }
//
// @Override
// public int hashCode() {
// int result = getMethodName().hashCode();
// result = 31 * result + getTotalTimeThreshold().hashCode();
// result = 31 * result + getOwnTimeThreshold().hashCode();
// result = 31 * result + getMeasuredTotalTime().hashCode();
// result = 31 * result + getMeasuredOwnTime().hashCode();
// return result;
// }
// }
// Path: dotTrace-server/src/test/java/jetbrains/buildServer/dotTrace/server/StatisticProviderTest.java
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.dotTrace.StatisticMessage;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.springframework.beans.factory.BeanFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
oneOf(myHistoryElement1).tryGetValue("ownTimeKey");
will(returnValue(new BigDecimal(32)));
oneOf(myValueAggregatorFirst).aggregate(new BigDecimal(32));
allowing(myValueAggregatorLast).isCompleted();
will(returnValue(false));
allowing(myValueAggregatorFirst).isCompleted();
will(returnValue(false));
oneOf(myHistoryElement2).tryGetValue("totalTimeKey");
will(returnValue(new BigDecimal(14)));
oneOf(myValueAggregatorLast).aggregate(new BigDecimal(14));
oneOf(myHistoryElement2).tryGetValue("ownTimeKey");
will(returnValue(new BigDecimal(36)));
oneOf(myValueAggregatorFirst).aggregate(new BigDecimal(36));
oneOf(myValueAggregatorLast).tryGetAggregatedValue();
will(returnValue(PREV_TOTAL_TIME));
oneOf(myValueAggregatorFirst).tryGetAggregatedValue();
will(returnValue(PREV_OWN_TIME));
}});
// When
final StatisticProvider instance = createInstance();
|
final Statistic statistic = instance.tryCreateStatistic(new StatisticMessage("method1", TOTAL_TIME_THRESHOLD_STR, OWN_TIME_THRESHOLD_STR, MEASURED_TOTAL_TIME_STR, MEASURED_OWN_TIME_STR), Arrays.asList(myHistoryElement1, myHistoryElement2));
|
JetBrains/teamcity-dottrace
|
dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/DotTraceSnapshotsPublisherTest.java
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
|
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.messages.serviceMessages.Message;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
|
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.dotTrace.agent;
public class DotTraceSnapshotsPublisherTest {
private Mockery myCtx;
private LoggerService myLoggerService;
private RunnerParametersService myRunnerParametersService;
private FileService myFileService;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
//noinspection unchecked
myLoggerService = myCtx.mock(LoggerService.class);
myRunnerParametersService = myCtx.mock(RunnerParametersService.class);
myFileService = myCtx.mock(FileService.class);
}
@Test
public void shouldSendSnapshotFileAsArtifactFileWhenHasNoParentDirectory() throws IOException {
// Given
final CommandLineExecutionContext executionContext = new CommandLineExecutionContext(0);
final File outputFile = new File("output");
final File snapshotsDir = new File("snapshotsDir");
myCtx.checking(new Expectations() {{
|
// Path: dotTrace-common/src/main/java/jetbrains/buildServer/dotTrace/Constants.java
// public class Constants {
// public static final String USE_VAR = "dot_trace";
// public static final String PATH_VAR = "dot_trace_path";
// public static final String THRESHOLDS_VAR = "dot_trace_thresholds";
// public static final String MEASURE_TYPE_VAR = "dot_trace_measure_type";
// public static final String PROFILE_CHILD_PROCESSES_VAR = "dot_trace_profile_child_processes";
// public static final String PROCESS_FILTERS_VAR = "dot_trace_process_filters";
// public static final String SNAPSHOTS_PATH_VAR = "dot_trace_snapshots_path";
// }
// Path: dotTrace-agent/src/test/java/jetbrains/buildServer/dotTrace/agent/DotTraceSnapshotsPublisherTest.java
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.dotTrace.Constants;
import jetbrains.buildServer.messages.serviceMessages.Message;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.dotTrace.agent;
public class DotTraceSnapshotsPublisherTest {
private Mockery myCtx;
private LoggerService myLoggerService;
private RunnerParametersService myRunnerParametersService;
private FileService myFileService;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
//noinspection unchecked
myLoggerService = myCtx.mock(LoggerService.class);
myRunnerParametersService = myCtx.mock(RunnerParametersService.class);
myFileService = myCtx.mock(FileService.class);
}
@Test
public void shouldSendSnapshotFileAsArtifactFileWhenHasNoParentDirectory() throws IOException {
// Given
final CommandLineExecutionContext executionContext = new CommandLineExecutionContext(0);
final File outputFile = new File("output");
final File snapshotsDir = new File("snapshotsDir");
myCtx.checking(new Expectations() {{
|
oneOf(myRunnerParametersService).tryGetRunnerParameter(Constants.SNAPSHOTS_PATH_VAR);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.